javascript - Promise 在 nodejs 中没有实现

标签 javascript node.js

我目前正在开发 nodejs 应用程序,其中一部分是测试一些 api 调用,然后作为 promise 返回,然后执行另一个功能。

所以 - 我正在使用以下两个函数遍历一系列 promise :

所有 api 的所有功能

function testAllApis(apiList, counter = 0){
  return new Promise(function(fulfill, reject){
    console.log(counter);
    if(counter == apiList.length){
      console.log('test1');
      fulfill();
      console.log('test2');
    }
    else {
      testSingleApi(apiList[counter]).then(() => {
        testAllApis(apiList, counter + 1);
      }).catch((e) => {
        console.log(e);
        reject(e);
        testAllApis(apiList, counter + 1);
      })
    }
  })
}

每个单独数组的函数

function testSingleApi(thisApi){
  return new Promise(function(fulfill, reject){
    var apiUrl = '/api/' + thisApi.substr(7).slice(0, -3) + '/testapi/';
    var options = {
      hostname: serverHost,
      port: serverPort,
      path: apiUrl,
      method: 'GET',
    };
    var req = http.request(options, (res) => {
      console.log(res.statusCode);
      fulfill(res.statusCode);
    });
    req.on('error', (e) => {
      reject(e.message);
    });
    req.end();
  });
}

当我在终端中调用它时,它会按预期运行,并且控制台会记录我正在进行的 api 调用的成功代码 (200),但在第三次之后,当“计数器”等于数组的长度时,它进入 testAllApis 函数中的 if 条件,控制台记录“test1”,然后是“test2”,并且根本不执行 fulfill()。

有没有人对此有任何见解?我对 promises 还是很陌生,并尝试在网上搜索此问题的解决方案,但这是一个非常具体的问题,所以想在这里发帖。

最佳答案

使用 reduce 顺序运行 promise 更容易:

var funcs = apiList.map((api) => testSingleApi(api));

var promiseSerial = (funcs) =>
  funcs.reduce((promise, func) =>
    promise.then(result = func().then(Array.prototype.concat.bind(result))),
    Promise.resolve([]));

promiseSerial(promises)
  .then(...)
  .catch(...);

关于javascript - Promise 在 nodejs 中没有实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44719157/

相关文章:

javascript - 即使使用 webcrypto-shim,crypto.subtle 也不存在

javascript - 显示div元素分页的具体长度

javascript - 逐行读取文件并在 node.js 中执行分析?

javascript - 将模块函数传递给另一个文件中的函数

javascript - Coda:在页面重新加载时自动清除 JavaScript 控制台?

javascript - 如何从另一个弹出窗口内的链接调用弹出窗口。 jQuery 移动

javascript - if语句中的Ejs无法读取未定义的属性 ' foo '

node.js - 如何在每次创建文章并将其保存在数据库中时生成 slug?

node.js - 在 KeystoneJS 中使用 S3File 处理图像

javascript - 如何在 Google Charts 中将图像设置为图例