How to wait for function's promise in JavaScript

江枫思渺然 提交于 2019-12-11 09:46:46

问题


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

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)


回答1:


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!

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


来源:https://stackoverflow.com/questions/47773824/how-to-wait-for-functions-promise-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!