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?