Skip to content

Instantly share code, notes, and snippets.

@SteGriff
Created February 9, 2023 16:14
Show Gist options
  • Save SteGriff/576f5fe6fa08b27f6c685eeac8d2943d to your computer and use it in GitHub Desktop.
Save SteGriff/576f5fe6fa08b27f6c685eeac8d2943d to your computer and use it in GitHub Desktop.
Async and promises in JS - a proof of concept for returning values from async fns
<html>
<head><style>div{margin:2em;} ul{padding:0;}</style>
<body>
<div>
<ul>
<li>Open the DevTools console</li>
<li>Press Go</li>
<li>Data will be fetched from server (<code>return await fetch().then()</code>)</li>
<li>Press Go again</li>
<li>Data will be returned locally from the async function (<code>return todos</code>)</li>
<li>Both returns (the await and the static list) are <code>then</code>-able in the <code>main<code> function</li>
</ul>
<button onclick="main()">Go</button>
<p>
See also <a href="https://stackoverflow.com/a/45349130">Using await within a Promise (SO)</a>,
<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function#rewriting_a_promise_chain_with_an_async_function">Rewriting a Promise chain with an async function (MDN)</a>
</p>
</div>
<script>
var todos = [];
function main(){
getTodos()
.then((data) => {
console.log("Handle", data);
window.todos = data;
})
.catch((error) => {
console.log("Caught error", error);
});
}
async function getTodos(){
console.log("Todos", todos);
if (todos.length)
{
console.log("Return existing");
return todos;
}
console.log("Fetch from server");
return await fetch('https://jsonplaceholder.typicode.com/todos')
.then(response => response.json());
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment