我可以等待1个等待中的2个异步操作吗?

Tem*_*Fix 2 javascript node.js async-await

我有一个节点模块,该模块可导出承诺并解析数据库连接。解决后,我将使用连接来查询记录,这是另一个异步操作。我可以在等待1个时执行这两个异步操作吗?

在这种情况下,查询异步调用取决于解析到数据库连接的异步承诺。

模组

module.exports = {
  db: new Promise((acc, rej) => {
      if (!db.authenticated) {
        sequelize.authenticate()
        .then((res) => {
            db.authenticated = true;
            acc(db);
        })
        .catch((err) => {
            rej(err)
        });
      } else {
        acc(db);
      }
  })
};
Run Code Online (Sandbox Code Playgroud)

用法

const db = require('../db/db.js').db;
const existingUser = await db.Person.findOne({where : {email : body.email}});
Run Code Online (Sandbox Code Playgroud)

Ray*_*ond 6

回应我的评论await Promise.all([first(), second()]);

promise.All()方法将返回单个诺言,当所有诺言作为可迭代项传递或当可迭代项不包含任何诺言时,该诺言最终将解决。它会拒绝并拒绝的第一个承诺的原因。

async function one() {
  return new Promise(resolve => {
    resolve('One')
  })
}

async function two() {
  return new Promise(resolve => {
    resolve('Two')
  })
}

async function run() {
  return await Promise.all([one(), two()]); // One await
}

run().then((response) => {
  // Access Individually
  console.log(response[0]); // One
  console.log(response[1]); // Two
  // Access Together
  console.log(response);
})
Run Code Online (Sandbox Code Playgroud)

并回复您最近的评论。如果第二个函数依赖于该参数,则将值从一个承诺传递到另一个。我们可能会做这样的事情。

例子2

async function first() {
  return new Promise(resolve => {
    resolve('First') // Resolve 'first'
  })
}

async function second(response) {
  return new Promise(resolve => {
    resolve(response); // first() ran, then we appended '& second', then resolve our second response
  })
}

async function run() {
  // Wait for first() response, then call second() with response + append 'second'
  return await first().then((response) => second(response + ' & second'))
}

run().then((response) => {
  // Output: first & second
  console.log(response)
})
Run Code Online (Sandbox Code Playgroud)

文档:promise.All()-MDN