Last active
May 12, 2019 13:13
-
-
Save shukn/c096abd1fe29f016ca2e5d50949b8542 to your computer and use it in GitHub Desktop.
async/wait調査
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var asyncFunc = async function () { | |
return 1; | |
} | |
asyncFunc().then( v => console.log(v)); | |
// 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var asyncFunc1 = async () =>{ return 1 }; | |
asyncFunc1() | |
.then( v => console.log(`then: ${v}`) ) | |
.catch( v => console.log(`catch: ${v}`) ); | |
// then: 1 | |
var asyncFunc2 = async () =>{ throw new Error('error')}; | |
asyncFunc2() | |
.then( v => console.log(`then: ${v}`) ) | |
.catch( v => console.log(`catch: ${v}`) ); | |
// catch: Error: error | |
// returnを明示しなかった場合はresolveになる | |
var asyncFunc3 = async () =>{ }; | |
asyncFunc3() | |
.then( v => console.log(`then: ${v}`) ) | |
.catch( v => console.log(`catch: ${v}`) ); | |
// then: undefined | |
// 明示的にPromiseオブジェクトを返却することもできる | |
var asyncFunc4 = async () => Promise.resolve(4); | |
asyncFunc4() | |
.then( v => console.log(`then: ${v}`) ) | |
.catch( v => console.log(`catch: ${v}`) ); | |
// then: 4 | |
var asyncFunc5 = async () => Promise.reject(5); | |
asyncFunc5() | |
.then( v => console.log(`then: ${v}`) ) | |
.catch( v => console.log(`catch: ${v}`) ); | |
// catch: 5 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var asyncFunc = async () => { | |
let promise = new Promise((resolve, reject) => { | |
setTimeout(() => resolve("success!"), 1000) | |
}); | |
let result = await promise; // promise が解決するまで待機 | |
console.log(result); | |
} | |
asyncFunc(); | |
// success! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// try ~ catch構文を使って処理 | |
var asyncFunc1 = async () => { | |
try { | |
var z = await Promise.reject(new Error('failed..')); // Errorオブジェクトがスローされる | |
} catch (e) { | |
console.log(e); | |
} | |
} | |
asyncFunc1(); | |
// Error: failed.. | |
// catchメソッドを使っても処理できる | |
var asyncFunc2 = async () => { | |
var z = await Promise.reject(new Error('failed..')).catch(console.log); | |
} | |
asyncFunc2(); | |
// Error: failed.. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment