Skip to content

Instantly share code, notes, and snippets.

@nobeans
Created November 1, 2016 09:06
Show Gist options
  • Select an option

  • Save nobeans/0710ae95a9739ca4307ba491d6bd6884 to your computer and use it in GitHub Desktop.

Select an option

Save nobeans/0710ae95a9739ca4307ba491d6bd6884 to your computer and use it in GitHub Desktop.
new Promise(() => {
console.log("begin");
try {
throw Error("HOGE: 1"); // new Promise()で明示rejectせずに例外をスローしてもreject扱いになる
} finally {
console.log("end");
}
}).catch((err) => { // ここが非同期実行
console.log("Catched error", err);
})
console.log("done");
//=>
// begin
// end
// done
// Catched error [Error: HOGE]
//
console.log("------------------------");
Promise.resolve() // resolveを使って本処理をthenから始めてしまうと、本処理=即非同期実行になってしまうことに注意
.then(() => {
console.log("begin");
try {
throw Error("HOGE: 2");
} finally {
console.log("end");
}
})
//.then(null, (err) => { // == catch
// console.log("second callback in then", err);
//})
.catch((err) => { // ここが非同期実行
console.log("Catched error", err);
})
console.log("done");
//=>
// begin
// end
// done
// ------------------------
// done
// Catched error [Error: HOGE: 1]
// begin
// end
// Catched error [Error: HOGE: 2]
console.log("------------------------");
new Promise((resolve) => {
console.log("begin");
try {
resolve("RESULT!"); // new Promise()のときは、resolveをしないと次のthenが発火しない!!!!
return;
} finally {
console.log("end");
}
})
.then((data) => {
console.log("Then1", data);
return data + "!!!!";
})
.then((data) => {
console.log("Then2", data);
})
.catch((err) => { // ここが非同期実行
console.log("Catched error", err);
})
console.log("done");
//=>
// begin
// end
// done
// ------------------------
// done
// ------------------------
// begin
// end
// done
// Catched error [Error: HOGE: 1]
// begin
// end
// Then1 RESULT!
// Catched error [Error: HOGE: 2]
// Then2 RESULT!!!!!
console.log("------------------------");
Promise.resolve().then(() => {
console.log("begin");
try {
return "RESULT!"; // then/catchの場合はreturnすればOK
} finally {
console.log("end");
}
})
.then((data) => {
console.log("Then1", data);
return data + "!!!!";
})
.then((data) => {
console.log("Then2", data);
})
.catch((err) => { // ここが非同期実行
console.log("Catched error", err);
})
console.log("done");
//=>
// begin
// end
// done
// ------------------------
// done
// ------------------------
// begin
// end
// done
// Catched error [Error: HOGE: 1]
// begin
// end
// Then1 RESULT!
// Catched error [Error: HOGE: 2]
// Then2 RESULT!!!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment