运行多个variable = function()并知道它们何时完成的最简洁方法是什么

时间:2018-05-07 16:22:31

标签: javascript node.js

在保存为JSON文件之前,我有多个需要计算的变量,这些变量是用函数计算的。但是,当异步运行时,它们会变为未定义。我读到了承诺,似乎这可能就是这样,但似乎有点愚蠢地运行15个承诺,所以我想我会问是否有更清洁的方法来做到这一点。这是代码的一部分



var sql = "Select a.Volume, a.LastPrice, a.buyers, a.id From (Select Volume, LastPrice, buyers, id FROM "+ marketname +" ORDER BY id DESC LIMIT 1440) a order by a.id asc";
          db.query(sql, function (err, result, fields) {
          if (err) throw err;
          result.forEach(function(element){
            results = result.length;
            tempArrayVol.push(element.Volume);
            tempArrayPrice.push(element.LastPrice);
            tempArrayBuyers.push(element.buyers);
            counter++;
            console.log(results + " " + counter);
          });
          
         var volumeaverage = (( tempArrayVol.reduce(function(acc, val) { return acc + val; }) )  / tempArrayVol.length);
         var buyersaverage = ((( tempArrayBuyers.reduce(function(acc, val) { return acc + val; }) ) / tempArrayBuyers.length ) * 100);

         var price24h    = change(prevDay, tempArrayPrice[tempArrayPrice.length -1]);
          //etc
          




因此,一旦定义了所有变量,应该编写JSON文件,我应该链接承诺还是有更好的方法?

1 个答案:

答案 0 :(得分:2)

Promises

Promise.all([
  function1(),
  function2(),
  function3(),
]).then(([res1, res2, res3]) => doSomething(res1,res2,res3));

async/await

async function() {
  const res1 = await func1();
  const res2 = await func2();
  const res3 = await func3();
  // do your thing
}