Promise and async/await Key Word

Eddy Gao
3 min readMar 5, 2021

--

Async/ await and promise confuses some of the javascript developers. I am one of them.

Yesterday I was solving a complex logic problem happening in my currently developing app.

I researched and tried so many ways to think of a way out before I use async/await keywords.

As starting of my code, I used Post.findbyId(postId).then(//somecondition return post).catch(//some error handling)

Then adjusting something inside the promise, such as how it returns and how it resolves. All the answer I got is either null, empty hash, or undefined. So I’m thinking that it’s because it goes to synchronous function and returns before the compromise resolved. Since the posts=>{} is a synchronous callback function of .then, and it doesn’t wait for the Promise to be done inside the synchronous map function.

So I started digging into the async/await solution. Since they can be another way of writing promises and in a more flexible way.

First I found a built-in function of Promise in javascript which is Promise.all, it helps to resolve multiple Promise at once. Then, I search for how to run a promise inside a map function. Then I got the solution of turning the callback of the map function into async function, and then await for promise inside the callback. Instead of resolving it inside the callback. Return all the promise of the map function. And then resolve it at once with the Promise.all.

After two hours I finally solve the problem.

After solving the problem I dive more into the async/await. Basically is an async keyword turns a function not only asynchronous also returns a Promise.

Since a promise is asynchronous, if I tried to resolve the result from the promise it’s going to wait for the synchronous function to finish.

For example, If I put a promise inside a map function it’s going to follow the synchronous order.

The map function runs before the sync() function because they’re both synchronous. But if I add async and await to the callback function, still synchronously, but the map function will return multiple promises.

The promise failed because the async function didn’t wait for the other promise.

After the Promise.all function comes in to resolve all the promises.

The promise is the art of javascript. It’s being used almost everywhere including REST-API, MongoDB, and it encrypts the data.

Source:

--

--

No responses yet