简体   繁体   English

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

[英]Can I await 2 async actions with 1 await?

I have a node module that exports a promise and resolves a database connection. 我有一个节点模块,该模块可导出承诺并解析数据库连接。 When it resolves I use the connection to query records which is another async operation. 解决后,我将使用连接来查询记录,这是另一个异步操作。 Can I do both of these async actions with 1 await? 我可以在等待1个时执行这两个异步操作吗?

In this case the querying async call is dependent on the async promise resolving to a db connection. 在这种情况下,查询异步调用取决于解析到数据库连接的异步承诺。

Module

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);
      }
  })
};

usage 用法

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

In response to my comment using await Promise.all([first(), second()]); 回应我的评论,使用await Promise.all([first(), second()]); :

The promise.All() method will return a single promise that finally resolves when all the promises pass as an iterable or when the iterable does not contain any promises. promise.All()方法将返回一个promise,当所有promise作为可迭代对象传递时或当可迭代对象不包含任何promise时,该promise将最终解析。 It will reject with the reason of the first promise that rejects. 它会拒绝并拒绝的第一个承诺的原因。

Example

 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); }) 

And to respond to your recent comment. 并回复您最近的评论。 To pass the value from one promise to the other, if the second function is dependent on that parameter. 如果第二个函数依赖于该参数,则将值从一个承诺传递到另一个。 We might do something like this. 我们可能会做这样的事情。

Example 2 例子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) }) 

Documentation: promise.All() - MDN 文档: promise.All()-MDN

In your comments you have mentioned you want to run two async calls after the other using await. 在您的评论中,您提到过要在另一个使用await之后运行两个异步调用。

The other answer has used promises to show you this behaviour. 另一个答案使用了承诺来向您展示这种行为。 How ever using await you can run two async calls much cleanly! 如何使用await可以很干净地运行两个异步调用! just do: 做就是了:

async twoAsyncCalls(){

    let firstResult = await first();
    //Things to do after first

    let secondResult = await second();
   //Things to do after second

    //To catch any async errors surround this code with a try catch block!

    return {/* return anything here*/}
    //This will be wrapped in a promise

}

So to answer your question you cannot sequentially run 2 async calls one after the other using just one await! 因此,要回答您的问题,您不能仅使用一个等待就依次运行2个异步调用! You need 2 await statements. 您需要2条等待语句。

Your code should be changed to this usage 您的代码应更改为此用法

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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