0

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();
partnerd
  • 53
  • 1
  • 5
  • "*In the code example, the whole call stack is async*" - no, the `(resolve) => {` function is not. And it's really supposed to only contain the `setTimeout` call and nothing else. Just move the `await writeSubSubObject();` and `await writeSubObject();` calls outside of the `new Promise`, into the `writeSubObject` (resp `writeMainObject`) body – Bergi Nov 24 '20 at 17:06
  • Ah, yes. Note to future readers: don't overlook anonymous functions passed and their potential need to be async when thinking "the whole stack is async." – partnerd Dec 09 '20 at 01:34

0 Answers0