Skip to content

Instantly share code, notes, and snippets.

@sota1235
Created June 6, 2018 14:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sota1235/85dd4ba3d516c2465805a875fc275d3e to your computer and use it in GitHub Desktop.
Save sota1235/85dd4ba3d516c2465805a875fc275d3e to your computer and use it in GitHub Desktop.
/** 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