Ben Aston Ben Aston - 1 year ago 60
Javascript Question

Do I have to await all the way down the call chain?

If I have an

async
function, do I have to repeatedly use the
await
keyword down the call chain, even if the methods being invoked are marked as
async
and use the
await
keyword themselves?



async function foo() {
const result = await bar(); // is this await required?
console.log(result);
}

async function bar() {
console.log('waiting...');
return await new Promise(resolve => setTimeout(() => resolve('result'), 1000)) ;
}




Answer Source

You do if you want the promise to be resolved.

Because

const result = bar();

is perfectly valid: it returns a promise.

Using await, you instruct the engine to wait for the promise to be resolved (or fail) and get the result. There are many valid cases where you would want to deal with the promise itself (for example adding operations) even inside an async function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download