问题描述
我只是从NodeJS开始.我尝试使用NodeJS进行循环,然后才将循环:将我的结果发送到快速模板.
I'm just starting with NodeJS. I try to do with NodeJS a loop and only then : send my result to an express template.
我尝试了许多lib和诺言,但没有一个奏效.节点在结束循环之前先执行然后"操作.
I tried many lib and promises but none of them worked. Node do "then" before ending the loop...
这是我的最后一次尝试,您可以帮我吗?非常感谢.
Here's my last try, can you help me with? Thanks a lot.
[...]
//pveIds contains list of dailies id (object)
var pveIds = body.pve;
//init tab, will contain dailies title
var pveNames = [];
Promise.map(pveIds, function(pveId) {
// Promise.map awaits for returned promises as well.
request.get({
url: 'https://api.guildwars2.com/v2/achievements?id=' + pveId.id,
json: true
},
function(error, response, body) {
console.log('log 1: ' + body.name);
if (response.statusCode == 200) {
return body.name;
}
}).on('data', function(v) {
console.log('log 2: ' + v);
return v;
});
}).then(function(results) {
console.log("done");
console.log(results);
console.log("names tab:" + pveNames);
res.render('pve.ejs', {
names: pveNames
});
});
推荐答案
您需要return request.get({...
而不只是request.get({
现在,函数(pveId)返回的状态不确定,因此Promise.map只会注册一堆未定义的内容,而不是实际的承诺.
The way you have it now your function(pveId) returns undefined so your Promise.map just registers a bunch of undefined's instead of actual promises.
您也不应将promise与回调混合使用,而应使用request-promise而不是request.
You should also not mix promises with callbacks, use request-promise instead of request.
这篇关于nodejs请求,循环和处理承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!