NodeJs forEach请求承诺在返回之前等待所有promise

时间:2015-09-11 11:12:10

标签: javascript node.js get promise

问题是我无法得到任何回报的承诺。他们......只是空着。

我在SO上看到的每个答案都告诉我这样做,尽管由于某些原因这不起作用。我在我的智慧结束,拔头发和粉碎键盘;有人可以指出我的愚蠢吗?

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
});

2 个答案:

答案 0 :(得分:4)

您将返回没有.then方法的延迟对象defer.promise,而不是Promise对象Promise.all

但无论如何,这是deferred antipattern,这里不需要使用延迟。只需返回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 }); } 获取您的承诺:

{{1}}

答案 1 :(得分:0)

所以,事实证明我正在解决承诺或某事。返回q.all()工作得非常好:))

function findSynonym(searchList) {
    var promises = [];

    var url = "http://thesaurus.altervista.org/service.php?word=%word%&language=en_US&output=json&key=txXYFyF4UgFiNsFY3oB7";
    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);
        });