考え方
-
new Promise
が実行した時点で、Promiseの中の処理は開始している。 - Promiseが実行した処理の結果や、終わったことを知りたいなら
then()
やcatch()
が必要。 -
then()
やcatch()
があってもなくても、Promiseの中の処理自体に影響はない。 - 非同期処理の完了を待ちたいなら、
then()
やcatch()
が必要。つまり、then()
やcatch()
は非同期処理を同期処理として扱えるようにできる。
new Promiseが実行した時点で、Promiseの中の処理は開始している
同期と非同期が混在
console.log("001");
setTimeout(() => {
console.log("002");
}, 2000);
console.log("003");
// 001
// 003
// 002
出力順を連番にする記述
①Promiseを使う
console.log("001");
new Promise<void>((resolve, reject) => {
setTimeout(() => {
console.log("002");
resolve();
}, 2000);
}).then(() => {
console.log("003");
});
// 001
// 002
// 003
@shiracamusさんにアドバイスいただいた内容を追記させていただきました。
②async awaitを使う
async function main() {
console.log("001");
await new Promise((resolve) => setTimeout(resolve, 2000));
console.log("002");
console.log("003");
}
main();
// 001
// 002
// 003
いけると思っていたけどうまくいかなかった記述
いけると思っていたけどうまくいかなかった記述
console.log("001");
const promise = new Promise<void>((resolve, reject) => {
setTimeout(() => {
resolve();
}, 2000);
});
// then()の部分だけ外だし
promise.then(() => console.log("002"));
console.log("003");
// 001
// 003
// 002
// これはpromiseの中の処理が"終わった後にやることを定義している"だけ。
// then()は非同期処理を待たせることはできない。
promise.then(() => console.log("002"));
async/awaitについて
asyncで定義すると戻り値はPromiseになる
// () => Promise<void>
const asyncFoo = async () => {};
// () => Promise<string>
const asyncApple = async () => "apple";
// () => Promise<never>
// neverは例外を返す関数の戻り値の型
const asyncError = async () => {
throw new Error("err");
};