如何在JavaScript中等待函数的承诺

如何在JavaScript中等待函数的承诺

本文介绍了如何在JavaScript中等待函数的承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Node.js应用程序中,我有一个函数,该函数遍历URL数组并获取其值,一旦完成循环,它将返回最终值作为Map。下面的代码。

In my Node.js app I have a function that loops over an array of URLs and get their values, once loop is done it will return the final value as a Map. Code following.

let getResults = function(urls){
    let results = new Map();
    let retrievePromises = [];
    urls.forEach(function (value, i) {
        retrievePromises.push(
            restAgent.get(value).then(function(data){
                for (let item of data.items) {
                    let name = item.filter(n => n.name === "somename"); //filter array
                    let obj = {};
                    obj.name = item.name;
                    obj.address = item.address;
                    results.set(name, obj);
                }

            }).catch(function(err){
                console.log(err);
            })
        );
    });

    Promise.all(retrievePromises).then(function(){
        return this.results;
    });
}

如果然后我运行, console.log(getResults ()); 会返回 undefined ,因为它在函数返回结果之前被触发。
如何解决此问题,并且由于我是Promises的新手,对代码有任何可能的改进吗? (我知道forEach不利)

If then I run, console.log(getResults()); it will return undefined as it is triggered before the function returns results.How to solve this issue, and since I am new to Promises, any possible improvements to the code? (I know that forEach is not favorable)

推荐答案

您必须返回 Promise 。对于您的情况,您将必须返回 Return Promise.all

You have to return the Promise. In your case you will have to return the return Promise.all

let getResults = function(urls){
    let results = new Map();
    let retrievePromises = [];
    urls.forEach(function (value, i) {
        retrievePromises.push(
            restAgent.get(value).then(function(data){
                for (let item of data.items) {
                    let name = item.filter(n => n.name === "somename"); //filter array
                    let obj = {};
                    obj.name = item.name;
                    obj.address = item.address;
                    results.set(name, obj);
                }

            }).catch(function(err){
                console.log(err);
            })
        );
    });

    return Promise.all(retrievePromises).then(function(){
        return results;
    });
}

不需要改进,您的代码是最佳的。做得好!

There is no need for improvements, you code code is optimal. Good job!

要检查结果,您必须在调用<$ c时执行 .then() $ c> getResults()。如果执行 console.log(getResults()); ,您将获得promise对象。

To check the results you will have to do .then() when you call getResults(). If you do console.log(getResults()); you will get the promise object.

要查看结果,您必须要做的事情

To see the result you have to do

getResults(urls).then(function(results){
    console.log(results);
})

这篇关于如何在JavaScript中等待函数的承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-26 00:07