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

2019-02-04 04:15 (7 years ago)
Differences in Behavior with and without Await in Functions that Create and Return Promises Inside JS Promises

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.
Please rate this article (No signup or login required)
Currently unrated

Related posts

The author runs the application development company Cyberneura.
We look forward to discussing your development needs.

Categories

Archive