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));
My question for Artash Grigoryan
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
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();
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))