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

178
Visualizações
JavaScript getting array index from promise

The script below returns promise, there is an array inside it with two index, i want to get index=0 and index=1 separately and output them, how can i do it without using console.log?

async function a1(callback) {
  var a = 2 + 2;
  return await [a, callback()];
}

async function a2() {
  var b = 2 + 3;
  return await b;
}
console.log(a1(a2));

enter image description here


My question for Artash Grigoryan

enter image description here

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

In javascript, async functions always return promise.

I am not entirely sure about your intentions here, but looking at your drawing I would assume that you need to add an extra await on lines 3 and 9. This code should work for you:

async function a1(callback) {
        var a = 2 + 2;
        return await [a, await callback()];
  }

async function a2() {
    var b = 2 + 3;
    return await b;
}
await a1(a2);

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

about 4 years ago · Juan Pablo Isaza Relatório

0

I don't really understand why without console.log, but You can do this:

async function main() {
  console.error(await a1(a2));
}

async function a1(callback) {
  var a = 2 + 2;
  return await [a, callback()];
}

async function a2() {
  var b = 2 + 3;
  return await b;
}

main();

about 4 years ago · Juan Pablo Isaza Relatório

0

a2 is an async function , so callback() wont be resolved here in this statement return await [a,callback()].

You can check if the callback is of type AsyncFunction , if so then you can wait for it to get resolved before returning the value

async function a1(callback) {
  var a = 2 + 2;
  if (callback.constructor.name === 'AsyncFunction') {
    const m = await callback().then(val => val)
    return [a, m]
  }
  return await [a, callback];
}

async function a2() {
  var b = 2 + 3;
  return await b;
}
a1(a2).then(d => console.log(d))

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