-1

I'm using a library called request-promise to make my calls to an API multiple times over a look with promises like so.

const rp = require('request-promise');

static buildProfileImageObject(personObj) {
    var promiseArr = [];
    var parsedPersonResponseObj = [];

    personObj.searchResult.hits.map(person => {
        let options = {
            method: 'GET',
            uri: `api.com/class/${person.ID}`,
            json: true
        }

        promiseArr.push(rp(options));
    });

    var resultsObj = null
    Promise.all(promiseArr)
        .then((results) => {
            resultsObj = results
            console.log(results)
        }).catch(err => {
            Utils.log("API Call Error", err)
            return Utils.errorResponse();
        });

    console.log("THIS IS AFTER");
    console.log(resultsObj);

    return resultsObj;
}

This calls the API perfectly and shows all the results when console.log(results) is hit.

My issue is that when this function is called I get a return of value of null because it's not waiting for Promise.all to finish. The response appears in my console after some time after the return is showing null

How do I wait for the Promises to finish and then return those results instead?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
BaconJuice
  • 3,739
  • 13
  • 56
  • 88

1 Answers1

1

Your function also needs to return a promise (or be an async function if your stack supports it, but I'll assume it doesn't).

const rp = require('request-promise');

static buildProfileImageObject(personObj) {
    const promises = personObj.searchResult.hits.map(person => rp({
        method: 'GET',
        uri: `api.com/class/${person.ID}`,
        json: true
    }));

    return Promise.all(promises).catch(err => {
        Utils.log("API Call Error", err)
        return Utils.errorResponse();
    });
}

Then you'd use this like

Something.buildProfileImageObject(person).then((results) => {
   console.log(results);
});
AKX
  • 152,115
  • 15
  • 115
  • 172