How to wait for function's promise in JavaScri

2019-07-23 07:24发布

问题:

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