TIL functional async/await
POSTED ON:
TAGS: promises javascript node
I struggle with getting async/await written correctly.
This is a simple example of async/await used to run a function asynchronously:
const doSomethingAsync = () => {
return new Promise((resolve) => {
setTimeout(() => resolve('I did something'), 3000)
})
}
const doSomething = async () => {
console.log(await doSomethingAsync())
}
console.log('Before');
doSomething();
console.log('After');
The above code will print the following to the browser console:
Before
After
I did something // after 3s
So the line of thinking is:
- We hit the console.log('Before');
- We fire off the
doSomething
function, which is going to return a Promise with a setTimeout. - We hit the console.log('After');
- We finally get the data back from
doSomething
, as it resolves it's Promise.
via The definitive Node.js handbook – Learn Node for Beginners
Related TILs
Tagged: promises