Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
73
rated 0 times [  80] [ 7]  / answers: 1 / hits: 71559  / 8 Years ago, mon, august 1, 2016, 12:00:00

Given the code samples below, is there any difference in behavior, and, if so, what are those differences?



return await promise



async function delay1Second() {
return (await delay(1000));
}


return promise



async function delay1Second() {
return delay(1000);
}


As I understand it, the first would have error-handling within the async function, and errors would bubble out of the async function's Promise. However, the second would require one less tick. Is this correct?



This snippet is just a common function to return a Promise for reference.



function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}

More From » async-await

 Answers
19

Most of the time, there is no observable difference between return and return await. Both versions of delay1Second have the exact same observable behavior (but depending on the implementation, the return await version might use slightly more memory because an intermediate Promise object might be created).



However, as @PitaJ pointed out, there is one case where there is a difference: if the return or return await is nested in a try-catch block. Consider this example



async function rejectionWithReturnAwait () {
try {
return await Promise.reject(new Error())
} catch (e) {
return 'Saved!'
}
}

async function rejectionWithReturn () {
try {
return Promise.reject(new Error())
} catch (e) {
return 'Saved!'
}
}


In the first version, the async function awaits the rejected promise before returning its result, which causes the rejection to be turned into an exception and the catch clause to be reached; the function will thus return a promise resolving to the string Saved!.



The second version of the function, however, does return the rejected promise directly without awaiting it within the async function, which means that the catch case is not called and the caller gets the rejection instead.


[#61184] Thursday, July 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
paulinap

Total Points: 346
Total Questions: 86
Total Answers: 97

Location: Dominican Republic
Member since Sun, Sep 4, 2022
2 Years ago
;