简体   繁体   English

当函数什么都不返回时的Node.js Promise.all

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

How to handle multiple calls to the same function when its returning nothing. 什么也不返回时如何处理对同一函数的多次调用。 I need to wait untill all calls are finished so i can call another function. 我需要等到所有调用完成后才能调用另一个函数。

For now I'm using Promise.all() but it doesn't seem right: 现在,我正在使用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
      }
    });
  });
}

This writes data to a database in multiple statements, i need to wait untill all are finished. 这会以多条语句将数据写入数据库,我需要等到所有操作完成后再进行操作。 Is this actually the "right" way to do it? 这实际上是“正确”的方法吗? I mean... it works, but i have the feeling it's not how you are supposed to do it. 我的意思是...它起作用了,但是我感觉这不是您应该怎么做。


Using Promise.all for your case is a good call, since it returns a Promise, when all the promises passed as an iterable are resolved. 在您的案例中使用Promise.all是一个很好的选择,因为当所有作为迭代对象传递的promise被解决时,它会返回Promise。 See the docs . 请参阅文档

However, for brevity and readability, try converting your insertValues into async-await function as follows. 但是,为简洁起见,请尝试按以下方式将insertValues转换为async-await函数。 This tutorial would be a great place to start learning about async functions in JavaScript. 教程是开始学习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);
  }
}

Here, insertValues() function doesn't return any value. 在此, insertValues()函数不会返回任何值。 Its operation on the database is entirely dependent on the query statement passed to it. 它对数据库的操作完全取决于传递给它的查询语句。 I wrapped it within a try-catch block so as to catch any errors that might arise while performing the operation (s) above. 我将其包装在try-catch块中,以捕获执行上述操作时可能出现的任何错误。 More details on handling errors using try-catch can be found here . 可以在此处找到有关使用try-catch处理错误的更多详细信息。

Your promisified write to database looks ok, so we can update code from another part. 您向数据库承诺的写入看起来不错,因此我们可以从另一部分更新代码。
Let's rewrite it a little to use async/await and 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)
   }
 })();

I use here IIFE to use await behaviour. 我在这里使用IIFE来使用await行为。

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

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