简体   繁体   中英

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 .

But anyway, that's the deferred antipattern , there's no need of using deferreds here. Just return the promise that Promise.all gets you:

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 :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM