This post did not solve my issue: await is only valid in async function
In the code example, the whole call stack is async as the referenced post advises.
In the code below, imagine writing to a database that creates a top level object and some sub-objects and sub-sub-objects. I reduced the problem to this code that creates one of each type of object, simulating a database delay with varying lengths of time using setTimeout(). The code fails with the await is used. Even if you comment that one out, but allow an await deeper in the call tree, it fails. It seems like it's wrapped in async to me. Works fine without the await.
Have I not followed the post's advice correctly? Maybe others have encountered this same problem.
async function writeMainObject() {
let time = 1000;
let promise = new Promise((resolve) => {
let subobjectPromise = writeSubobject();
// - - - HERE IS THE OFFENDING LINE. - - -
// But even if you remove THIS await ... (see below)
await subobjectPromise;
setTimeout(() => {
console.log('resolving main object');
resolve('main object');
}, time);
});
return promise;
};
async function writeSubobject() {
let time = 3000;
let promise = new Promise((resolve) => {
let subSubObjectPromise = writeSubSubObject();
// OFFENDING LINE DEEPER IN STACK
// And await even deeper in the async call stack:
await subSubObjectPromise;
setTimeout(() => {
console.log('resolving sub-object');
resolve('sub-object');
}, time);
});
return promise;
};
async function writeSubSubObject() {
let time = 2000;
let promise = new Promise((resolve) => {
setTimeout(() => {
console.log('resolving sub-sub-object');
resolve('sub-sub-object');
}, time);
});
return promise;
};
let mainThing = writeMainObject();