NodeJs forEach请求承诺在返回之前等待所有诺言 [英] NodeJs forEach request-promise wait for all promises before returning

查看:94
本文介绍了NodeJs forEach请求承诺在返回之前等待所有诺言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是我无法兑现任何承诺.他们..只是空了.

Problem is I'm not able to get the promises to return anything. they.. just come empty.

我在SO上看到的每个答案都告诉我要做这个,尽管出于某些原因这是行不通的.我不知所措,拉头发,砸键盘.有人可以指出我的愚蠢吗?

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

推荐答案

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

You're returning the Deferred object defer, which does not have a .then method, instead of the Promise object defer.promise.

但是无论如何,这就是延迟反模式,这里不需要使用延迟.只需返回Promise.all会带给您的诺言即可:

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

这篇关于NodeJs forEach请求承诺在返回之前等待所有诺言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆