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

277
Visualizações
Javascript (Chrome Extension): How to correctly execute multiple API calls using fetch and force code to wait for the calls to finish?

I am trying to create a chrome extension using the gmail api. I am using an api call to get certain info, and then loop through the results and execute another api call per result. Once those calls finish, then the rest of the code will run. The issue that I am facing right now is that the rest of the code is executing before the fetches are returning the info.

Below is the function that is not working. I added 4 flags in the code to illustrate the problem better. The correct behavior should output flag 1, then loop 2, then loop 3, then 4. However, the actual behavior outputs flag 1 then loop 2 then 4, and then looping through flag 3.

One theory I have is that the cause is that I am using fetches inside of .then(). If this is the issue, how do I fix this? Or does it have anything to do with fetch being async? Any advice or helpful links would be super appreciated.

Thanks so much!

  let senderList = new Array();
  let init = {
    method: 'GET',
    async: true,
    headers: {
      Authorization: 'Bearer ' + token,
      'Content-Type': 'application/json'
    },
    'contentType': 'json'
  };
  fetch(
    'https://gmail.googleapis.com/gmail/v1/users/me/messages?key=ABCDEFGHIJKLMNOPQRSTUVWXYZ1234',
    init)
    .then((response) => response.json())
    .then(function(data) {
      console.log("Flag 1")
      let messageResponse = data.messages; //Array of Message Objects
      for (let i = 0; i < messageResponse.length; i++) {
        console.log("Flag 2")
        fetch(
          'https://gmail.googleapis.com/gmail/v1/users/me/messages/' + messageResponse[i].id +
              '?key=ABCDEFGHIJKLMNOPQRSTUVWXYZ1234',
          init)
          .then((response) => response.json())
          .then(function(message) {
            let headers = message.payload.headers;
            console.log("Flag 3")
            for (let i = 0; i < headers.length; i++) {
              if (headers[i].name == 'From'){
                senderList.push(headers[i].value);
              }              
            }               
          });          
      }
    }).then(function() {
      console.log("Flag 4")
      onSuccess(senderList);
    });        
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Use async/await syntax with Promise.all that resolves when all promises are fulfilled:

run();

async function run() {
  const list = await getSenderList();
  console.log(list, list.errors);
}

async function getSenderList() {
  const API_URL = 'https://gmail.googleapis.com/gmail/v1/users/me/messages/';
  const API_KEY = '?key=...';
  const INIT = {method: 'GET', /* ... etc. */ };
  const data = await fetchJson(API_URL + API_KEY);
  const senderList = [];
  senderList.errors = {};
  await Promise.all(data.messages.map(async msg => {
    const msgData = await fetchJson(API_URL + msg.id + API_KEY, INIT);
    if (msgData instanceof Error) {
      senderList.errors[msg.id] = msgData;
      return;
    }
    const headers = msgData.payload.headers;
    for (const h of headers) {
      if (h.name === 'From') {
        senderList.push(h.value);
      }
    }
  }));
  return senderList;
}

function fetchJson(url, init) {
  return fetch(url, init).then(r => r.json()).catch(err => err);
}
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