Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await a promise?

I just started learning NodeJS, and pushed by c# knowledge I'm trying the async / await operator, anyway, I need to ask how can I await a promise to get the result, in particular:

const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);

the code above generate an hash using the user password and a salt. This works like a charm, but suppose that I want break the code as the following:

 const hash = await bcrypt.genSalt(10, async (err, salt) =>  {
        return await bcrypt.hash(user.password, salt);
 });

I will get undefined, what I did wrong?

Is the first or second version better? Just to start me on this way.

Thanks in advance.

like image 252
teres Avatar asked Mar 07 '19 10:03

teres


People also ask

Can you only await a promise?

You can only usefully await a promise. map will return an array, so you can't usefully await it. If someFunction returns a promise, then the map will return an array of promises, which you could wrap with Promise.

How do you wait until your promise is resolved?

You can use the async/await syntax or call the . then() method on a promise to wait for it to resolve. Inside of functions marked with the async keyword, you can use await to wait for the promises to resolve before continuing to the next line of the function.

Should you await promises?

No, you don't always need to await a promise. But, to ensure proper application flow, you should always be ready to handle any error that occurs.

Is await the same as promise?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.


2 Answers

It is necessary a clarification:

  • an async return a Promise
  • await resolve "thenable" functions, like Promise

So, using the await in a callback-style can't works.

This is an example with your mixed-up callback + async/await in order to understand better how they work.

function getMyHash(password) {
  return new Promise((resolve, reject) => {
    bcrypt.genSalt(10, async (err, salt) => {
      if (err) {
        reject(err)
        return
      }
      try {
        const hash = await bcrypt.hash(password, salt);
        resolve(hash)
      } catch (err) {
        reject(err)
      }
    });
  })
}

function async doSomething() {
  const hash = await getMyHash(user.password)
}

I suggest you to choose one pattern and not mixing up together because could become really hard to read and affect performance (callback are always faster then promise)

like image 36
Manuel Spigolon Avatar answered Sep 28 '22 16:09

Manuel Spigolon


You are mixing up callback and async/await which are two different tools used to deal with asynchronous calls.


* async/await pattern *

Here we are calling genSalt() which returns a Promise object that you resolve (wait for the operation to be done).

const hash = await bcrypt.genSalt(10);

* callback pattern *

Here we are calling genSalt() which will call the provided function as callback when finished.

bcrypt.genSalt(10, () => {
   // Callback
});

Theses are two distinct method to handle asynchronous functions.



So the following example are working :

// async/await pattern
const salt = await bcrypt.genSalt(10);
const hash = await bcrypt.hash(user.password, salt);

// callback pattern
function generate(callback) {
   bcrypt.genSalt(10, (salt) => {
     bcrypt.hash(user.password, salt, (hash) => {
        callback(hash);
     });
   });
}


EDIT : To answer "Is the first or second version better?"


Javascript have history. Every year a new version of the norm ECMA is made up, like ECMA2015, ECMA2016, ECMA2017 ...

In vanilla js they were callbacks, in ES5 they were promises, in ES6 they were async/await.

async/await are the future. Be a part of the future!

like image 151
Orelsanpls Avatar answered Sep 28 '22 15:09

Orelsanpls