簡體   English   中英

我可以等待1個等待中的2個異步操作嗎?

[英]Can I await 2 async actions with 1 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);
      }
  })
};

用法

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

回應我的評論,使用await Promise.all([first(), second()]);

promise.All()方法將返回一個promise,當所有promise作為可迭代對象傳遞時或當可迭代對象不包含任何promise時,該promise將最終解析。 它會拒絕並拒絕的第一個承諾的原因。

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

並回復您最近的評論。 如果第二個函數依賴於該參數,則將值從一個承諾傳遞到另一個。 我們可能會做這樣的事情。

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

文檔: promise.All()-MDN

在您的評論中,您提到過要在另一個使用await之后運行兩個異步調用。

另一個答案使用了承諾來向您展示這種行為。 如何使用await可以很干凈地運行兩個異步調用! 做就是了:

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

}

因此,要回答您的問題,您不能僅使用一個等待就依次運行2個異步調用! 您需要2條等待語句。

您的代碼應更改為此用法

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