Home > Enterprise >  Am I using Promise.all correctly?
Am I using Promise.all correctly?

Time:12-02

I am using it many places in my code and it works. but at one place it didn't give any error, also did not give me the desired result. and when I show my code to the support forum they suggest that "You are using the JS object/class “Promise” incorrectly."

Can Anyone guide me on what's wrong with my code here is my code sample:

let charity = {};
      await Promise.all(
        charity = charityData.map(function( data ) {
              let address = data.zipCode
              let url = "https://maps.googleapis.com/maps/api/geocode/json?&address=" `'${address}'` "&key=***Google geocoding Key***"; //client's Key
              let urlResponse = Backendless.Request.get(url)    
               // let latitude = urlResponse.results[0].geometry.location.lat;
               // let longitude = urlResponse.results[0].geometry.location.lng;
              //let updateCharitiesData = {'objectId': data.objectId, 'latitude':latitude, 'longitude':longitude};
              return urlResponse;
        })
      );
    return charity;

CodePudding user response:

Almost. Assuming Backendless.Request.[method] returns a promise it would be more correct to do something along the lines of:

async function getCharityData() {
    const charity = await Promise.all(charityData.map( async function(data) {
       const address = data.zipCode;
       const url =
        `https://maps.googleapis.com/maps/api/geocode/json?&address=${address}&key=***Google geocoding Key***`; //client's Key
       const urlResponse = await Backendless.Request.get(url);
       return urlResponse;
   }));

   return charity
}

Promise.all requires an array as its argument to work correctly; passing an Array.map here and assigning the returned value to charity both ensures your Promise.all runs as expected and the returned array is an array of resolved promises.

CodePudding user response:

I would do it like this:

function getCharityData() {
    // `charity` is an array of Promises that will each resolve to 
    // a response.
    const charity = charityData.map((data) => {
        let address = data.zipCode;
        let url = 'https://maps.googleapis.com/maps/api/geocode'
        let urlResponse = Backendless.Request.get(url);
        return urlResponse;
    });
    return Promise.all(charity);
}
try {
    const charityData = await getCharityData();
} catch (e) {
    console.error(e);
}

This way, charityData will be an array of fetched responses.

In your code, the result of Promise.all() is never assigned to charity before it's returned, and that is the value you want.


CodePudding user response:

If you have access to Async/Await I'd simply do the following:

function getCharityData(charityData) {
let results = [];

for (let i = 0; i < charityData.length; i  ) {
    let url = `https://maps.googleapis.com/maps/api/geocode/json?&address=${charityData[i].zipCode}&key=***Google geocoding Key***`;

    try {
        let result = await Backendless.Request.get(url);

        results.push(result);
    } catch (err) {
        console.log("Oh dear!");
    }
}

return results;

}

For your use case, there's no need to use any Promise libraries when you have Async/Await, good old fashioned for loops and await (I'd personally prefer to do this sort of call sequentially instead of in parallel like Promise.all implores when I'm querying external APIs. This also ensures we don't fail fast like Promise.all does.).

  • Related