簡體   English   中英

當函數什么都不返回時的Node.js Promise.all

[英]Node.js Promise.all when function returns nothing

什么也不返回時如何處理對同一函數的多次調用。 我需要等到所有調用完成后才能調用另一個函數。

現在,我正在使用Promise.all()但它似乎不正確:

 Promise.all(table_statements.map(i => insertValues(i)))
     .then(function(result) {
       readNodeData(session, nodes);
     })
     .catch(function() {
       console.log(err);
     })

function insertValues(statement) {
  return new Promise((res, rej) => {
    database.query(statement, function (err, result) {
      if (err) {
        rej(err)
      }
      else{
       console.log("Daten in Tabelle geschrieben")
       res(); // basically returning nothing
      }
    });
  });
}

這會以多條語句將數據寫入數據庫,我需要等到所有操作完成后再進行操作。 這實際上是“正確”的方法嗎? 我的意思是...它起作用了,但是我感覺這不是您應該怎么做。


在您的案例中使用Promise.all是一個很好的選擇,因為當所有作為迭代對象傳遞的promise被解決時,它會返回Promise。 請參閱文檔

但是,為簡潔起見,請嘗試按以下方式將insertValues轉換為async-await函數。 教程是開始學習JavaScript異步功能的好地方。

// async insertValues function - for re-usability (and perhaps easy unit testing),
// I've passed the database as an argument to the function
async function insertValues(database, statement) {
  try {
    await database.query(statement);
  } catch (error) {
    console.error(error);
  }
}

// using the insertValues() function
async function updateDatabase(database) {
  try {
    // I am using 'await' here to get the resolved value.
    // I'm not sure this is the direction you want to take.
    const results = await Promise.all(
      tableStatements.map(statement => insertValues(database, statement))
    );
    // do stuff with 'results'.. I'm just going to log them to the console
    console.log(results);
  } catch (error) {
    console.error(error);
  }
}

在此, insertValues()函數不會返回任何值。 它對數據庫的操作完全取決於傳遞給它的查詢語句。 我將其包裝在try-catch塊中,以捕獲執行上述操作時可能出現的任何錯誤。 可以在此處找到有關使用try-catch處理錯誤的更多詳細信息。

您向數據庫承諾的寫入看起來不錯,因此我們可以從另一部分更新代碼。
讓我們用async/awaittry/catch重寫一下。

 (async() => {
   const promisifiedStatements = table_statements.map(i => insertValues(i));

   try {
     await Promise.all(promisifiedStatements);
     readNodeData(session, nodes);
   } catch(e){
     console.log(e)
   }
 })();

我在這里使用IIFE來使用await行為。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM