Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

171
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!