简体   繁体   中英

Benefits from async await vs return promise

I'm just trying to understand the benefits of this:

const populateUsers = done => {
  User.remove({}).then(async () => {
    const userOne = new User(users[0]).save();
    const userTwo = new User(users[1]).save();
    const usersProm = await Promise.all([userOne, userTwo]).then(() => done());
    return usersProm;
  });
};

over this:

const populateUsers = done => {
  User.remove({})
    .then(() => {
      const userOne = new User(users[0]).save();
      const userTwo = new User(users[1]).save();

      return Promise.all([userOne, userTwo]);
    })
    .then(() => done());
};

I came to this problem because eslint suggested my to use async in this function, and I remember the concept, make it work in my app, but I'm not sure why should I use this instead of the original way

Your first version does not go all the way . Do this:

const populateUsers = done => {
  User.remove({}).then(async () => {
    const userOne = new User(users[0]).save();
    const userTwo = new User(users[1]).save();
    await Promise.all([userOne, userTwo]);
    const usersProm = await done();
    return usersProm;
  });
};

There is no difference, it is just that code without these then callbacks is somewhat easier to read.

You might even apply it to the outer function:

const populateUsers = async () => {
  await User.remove({});
  const userOne = new User(users[0]).save();
  const userTwo = new User(users[1]).save();
  await Promise.all([userOne, userTwo]);
  const usersProm = await done();
  return usersProm;
};

Now populateUsers returns the promise instead of undefined .

As concluded in comments: you get an error because populateUsers returns a promise and accepts a done callback argument, while one of these is expected, not both.

Your original code was totally fine.

No, there is no benefit in using the code from your first snippet. You should avoid mixing await and .then(…) syntax ! To use async / await , you'd make the whole function async , not the then callback:

async function populateUsers(done) {
  await User.remove({})
  const userOne = new User(users[0]).save();
  const userTwo = new User(users[1]).save();

  await Promise.all([userOne, userTwo]);
  return done();
}

(Probably you would also remove that done callback - the function already returns a promise)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM