简体   繁体   中英

Multiple resolve() calls inside promise returning async function

I have the following testAsync function that should return resolved promise after I call resolve() .

async function wait(time) {
    await new Promise((resolve, reject) => { setTimeout(resolve, time) });
}

async function testAsync(testParam) {
    return new Promise(async (resolve, reject) => {
        try {
            await wait(2000); // do some async work
            if (testParam === 1) {
                console.log("test param is equal to 1");
                resolve("first IF");
            }
            if (testParam < 10) {
                console.log("test param is smaller than 10");
                resolve("second IF");
            }
        } catch (error) {
            reject(error);
        }
    });
}

(async () => {
    let result = await testAsync(1);
    console.log(result);
})();

console output:

test param is equal to 1
test param is smaller than 10
first IF

My problem is that if I structure the code in a way that includes more calls to resolve() that are not exclusive, the code does resolves the first one it hits but it does not stop and return in that place. Why does it continue? Is resolve() not loosely equal to return ? Should I just add return after every resolve() call?

return new Promise(async (resolve, reject) => { is antipattern. Adding async in front of a function will already return a Promise. new Promise has to be only used to convert a none Promise base async function into one that uses a Promise.

Is resolve() not loosely equal to return?

It is only equal in the sense, that it sets the "return" value of the promise, but it does not break the execution flow. So yes you would need to place a return after a resolve if you want to prevent that the following up code is executed.

But as I already said, the shown construct is anyway an anti-pattern and testAsync should look like this:

async function testAsync(testParam) {
  await wait(2000); // do some async work

  if (testParam === 1) {
    console.log("test param is equal to 1");
    return "first IF";
  }

  if (testParam < 10) {
    console.log("test param is smaller than 10");
    return "second IF";
  }
}

And the wait would more likely be written that way:

function wait(time) {
    return new Promise((resolve, reject) => { setTimeout(resolve, time) });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM