Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

89
Visualizações
Am I using Promise.all correctly?

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;
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

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.

about 4 years ago · Juan Pablo Isaza Relatório

0

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.


about 4 years ago · Juan Pablo Isaza Relatório

0

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.).

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda