Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading