[英]NodeJs forEach request-promise wait for all promises before returning
Problem is I'm not able to get the promises to return anything.问题是我无法得到返回任何东西的承诺。 they.. just come empty.他们..只是空的。
Every answer I see here on SO is telling me to do just this, though for some reason this is not working.我在这里看到的每个答案都告诉我这样做,尽管由于某种原因这不起作用。 I'm at my wits end, pulling hair and smashing keyboards;我不知所措,扯头发,砸键盘; Can someone pin-point my dumbness?有人可以指出我的愚蠢吗?
var q = require('q');
var request = require('request-promise'); // https://www.npmjs.com/package/request-promise
function findSynonym(searchList) {
var defer = q.defer();
var promises = [];
var url = "http://thesaurus.altervista.org/service.php?word=%word%&language=en_US&output=json&key=awesomekeyisawesome";
var wURL;
searchList.forEach(function(word){
wURL = url.replace('%word%',word);
promises.push(request(wURL));
});
q.all(promises).then(function(data){
console.log('after all->', data); // data is empty
defer.resolve();
});
return defer;
}
var search = ['cookie', 'performance', 'danger'];
findSynonym(search).then(function(supposedDataFromAllPromises) { // TypeError: undefined is not a function [then is not a function]
console.log('->',supposedDataFromAllPromises); // this never happens
});
You're returning the Deferred object defer
, which does not have a .then
method, instead of the Promise object defer.promise
.您传回递延对象defer
,其中没有一个.then
,而不是承诺对象的方法, defer.promise
。
But anyway, that's the deferred antipattern , there's no need of using deferreds here.但无论如何,这就是deferred antipattern ,这里没有必要使用 deferreds 。 Just return the promise that Promise.all
gets you:只需返回Promise.all
您提供的承诺:
function findSynonym(searchList) {
var url = "http://thesaurus.altervista.org/service.php?word=%word%&language=en_US&output=json&key=awesomekeyisawesome";
var promises = searchList.map(function(word) {
return request(url.replace('%word%', word));
});
return q.all(promises).then(function(data){
console.log('after all->', data); // data is empty
return undefined; // that's what you were resolve()ing with
});
}
So, turns out I was resolving the promises or something something.所以,事实证明我正在解决承诺或其他事情。 returning the q.all()
worked pretty well :)返回q.all()
效果很好:)
function findSynonym(searchList) {
var promises = [];
var url = "http://thesaurus.altervista.org/service.php?word=%word%&language=en_US&output=json&key=REDACTED";
var wURL;
searchList.forEach(function(word){
wURL = url.replace('%word%',word);
promises.push(request({url:wURL}));
});
return q.all(promises);
}
var search = ['cookie', 'performance', 'danger'];
findSynonym(search)
.then(function(a){
console.log('->',a);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.