JS Promise を中で作って Promise を返すファンクション await ありなしの動作の差

投稿者: ytyng 5年, 2ヶ月 前

resolveされるかされないか。

/**
* なにかプロミスがあって
* @returns {Promise<string>}
*/
function anyPromise(label) {
return new Promise((resolve, reject) => {
console.log(label, 'resolve');
resolve('succes.');
});
}

/**
* ケース1
* await してプロミス返す
* @returns {Promise<string>}
*/
async function awaitPromiseReturn() {
return await anyPromise('await:');
}

/**
* ケース2
* そのままプロミス返す
* @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);
});
}
// 結果
await: resolve
await: Promise { <pending> }
no-await: resolve
no-await: Promise { 'succes.' }
no-await: succes.
await: succes.
現在未評価

コメント

アーカイブ

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