Created
June 6, 2018 14:39
-
-
Save sota1235/85dd4ba3d516c2465805a875fc275d3e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** async functionの話 */ | |
// いつものPromise | |
const a = () => { | |
return new Promise((resolve, reject) => { | |
resolve(1); | |
}); | |
}; | |
// async function | |
const b = async () => { | |
// async内ではreturnしたものがPromiseのresolveにあたる | |
// asyncの返り値は必ずPromiseインスタンスになる | |
return 2; | |
}; | |
a().then(data => { console.log(data); }); // 1 | |
b().then(data => { console.log(data); }); // 2 | |
/** awaitの話 */ | |
const c = () => { | |
return new Promise((resolve, reject) => { | |
resolve(3); | |
}); | |
}; | |
const d = async () => { | |
return 4; | |
}; | |
const main = async () => { | |
const resultC = await c(); | |
const resultD = await d(); | |
// async内ではawait構文が使える | |
// awaitの引数にはPromiseインスタンスが入る | |
// awaitすると非同期処理でも結果を待ってから次の行に進む | |
// ただしasync function外の処理はブロッキングしない | |
return resultC + resultD; | |
}; | |
main().then(data => { console.log(data); }); // 7 | |
/** catch, 例外の話 */ | |
const promiseException = () => { | |
return new Promise((resolve, reject) => { | |
reject('Promise error'); | |
}); | |
}; | |
const asyncAwaitException = async () => { | |
throw new Error('async-await error'); | |
}; | |
promiseException() | |
.catch(err => { console.log(err.message); }); // Promise error | |
asyncAwaitException() | |
.catch(err => { console.log(err.message); }); // async-await error | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment