If you call an async function from non-async code, anything after the await runs asynchronously with respect to the caller:
async function asyncInner() {
console.log('before asyncInner');
await Promise.resolve()
console.log('after asyncInner');
}
console.log('start');
asyncInner()
console.log('end');
In other words, this prints:
start
before asyncInner
end
after asyncInner
But if you call this async function from within another async function:
async function asyncInner() {
console.log('before asyncInner');
await Promise.resolve()
console.log('after asyncInner');
}
async function asyncOuter() {
console.log('before asyncOuter');
await asyncInner();
console.log('after asyncOuter');
}
console.log('start');
asyncOuter()
console.log('end');
you get:
start
before asyncOuter
before asyncInner
end
after asyncInner
after asyncOuter
In other words, the inner method completes synchronously with respect to the outer method. Why is this and how could it be written so that asyncOuter completed before the asyncInner?
(I know I could use a setTimeout for this, but I'd prefer to avoid using callbacks, because one of the nice things about async is avoiding callback hell.)
the inner method completes synchronouslyNo it doesn't, that's maybe were your getting confused.