Refactoring JS Promises into async functions
Two key points:
- An async function in JS returns a promise;
- A promise in JS can be awaited with
So, a piece of code that uses promises with chains of
thing().then() can be refactored to use
Here is a JS example page which mixes promises and await. You can View Source and then download it to your PC to mess around and try changing other things.
If you modify the code to
console.log the return value of the
getTodos function, you can see that the first time it’s called it returns a
Promise<pending> and the second time it returns a
Here’s a second example which does the above for you!