Returning another aysnc function in resolve

Viewed 48

I have a function call like so:

await someFunction(foo);

With someFunction defined like:

const someFunction = foo => {
  return new Promise((resolve, reject) => {
    if (foo) {
      return resolve(someOtherPromise());
    }
    reject();
  }
}

Is this valid code? I have tested it and it seems ok.

Is it correct that await someFunction() will transform to await someOtherPromise() if foo is true i.e. will it continue waiting for someOtherPromise to resolve?

3 Answers

Yes, it is valid code and works by resolving with a promise, but smells like the Promise constructor antipattern. I would instead recommend to write

function someFunction(foo) {
  if (foo)
    return someOtherPromise();
  else
    return Promise.reject();
}

or

async function someFunction(foo) {
  if (foo)
    return someOtherPromise();
  else
    throw;
}

(and better throw a new Error with a message, not undefined)

I've written some test code to see if it's true:

const someFunction = foo => {
  return new Promise((resolve, reject) => {
    if (foo) {
      return resolve(someOtherPromise(2000));
    }
    reject();
  });
}

const someOtherPromise = async(ms) => {
    return new Promise(resolve => setTimeout(() => {
        console.log("i'm about to resolve in someOtherPromise");
        resolve();
    }, ms));
}


const run = async () => {
    await someFunction('foo');
    console.log('finished waiting for someFunction');
}

run();

I have written 3 function to test it out.

c = () => new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('c');
        resolve();
    }, 1000);
});
b = () => new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log('b');
        resolve(c());
    }, 1000);
});

a = async () => {
    console.log('a before');
    await b();
    console.log('a after');
};

a();

As we can see, the output order is a before, b, c then a after. So await had waited for b and continued waiting for c.

Related