繁体   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