Today I Learned - Rocky Kev

TIL functional async/await

POSTED ON:

TAGS:

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:

  1. We hit the console.log('Before');
  2. We fire off the doSomething function, which is going to return a Promise with a setTimeout.
  3. We hit the console.log('After');
  4. 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:

TIL functional async/await

PLACEHOLDER

TIL not using try/catch block with promises for error catching

You shouldn't use a try/catch block inside the Promise Definition. Your promise is already doing that.

TIL AggregateError

I heard the term AggregateError in relations to 'Promise.Any', So it's several errors wrapped in a array. That's all.