我目前正在开发 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/