Differences in Behavior with and without Await in Functions that Create and Return Promises Inside JS Promises

2019-02-04 13:15 (5 years ago) ytyng

Whether it gets resolved or not.

/**
* There is a promise
* @returns {Promise<string>}
*/
function anyPromise(label) {
return new Promise((resolve, reject) => {
console.log(label, 'resolve');
resolve('success.');
});
}

/**
* Case 1
* Await and return a promise
* @returns {Promise<string>}
*/
async function awaitPromiseReturn() {
return await anyPromise('await:');
}

/**
* Case 2
* Return the promise directly
* @returns {Promise<string>}
*/
function promiseReturn() {
return anyPromise('no-await:');
}

{
const p = awaitPromiseReturn();
console.log('await:', p);

p.then((text) => {
console.log('await:', text);
});
}

{
const p = promiseReturn();
console.log('no-await:', p);

p.then((text) => {
console.log('no-await:', text);
});
}
// Result
await: resolve
await: Promise { <pending> }
no-await: resolve
no-await: Promise { 'success.' }
no-await: success.
await: success.
Currently unrated

Comments

Archive

2025
2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011