循环节点异步函数数组

时间:2018-04-14 07:09:59

标签: javascript arrays loops

下面的代码是节点给出未定义的如何从包含异步函数的数组中获取console.log。我尝试过的承诺仍然无法

const fs = require("fs");
const path = require("path")
var req = {},
  res = {},
  previous = {};
var reqOBj = [];
var use = function(fun) {
  reqOBj.push(fun)
}
use(function(req, res, previous) {
  fs.readFile(path.join(__dirname, "/index.html"), "utf8", function(err, data) {
    if (err) {
      return false;
    } else {
      return previous;
    }
  })
})
use(function(req, res, previous) {
  previous.mid = '2nd';
  return previous;
})
for (let index = 0; index < reqOBj.length; index++) {
  console.log(reqOBj[index](req, res, previous));
}

1 个答案:

答案 0 :(得分:0)

reqOBj中的函数转换为返回promises的函数,然后将await转换为底部循环中promise的解析:

use(function(req, res, previous){
  return new Promise((resolve, reject) => {
    fs.readFile(path.join(__dirname , "/index.html"), "utf8", function(err, data){
      if(err) reject();
      else resolve(previous)
    });
  });
});
use(function(req, res, previous){
  previous.mid = '2nd';
  return previous;
});
(async () => {
  for (let index = 0; index < reqOBj.length; index++) {
    console.log (await reqOBj[index](req, res, previous));
  }
})();