1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【TS】Promiseのメモ

Last updated at Posted at 2024-12-06

考え方

  • 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");
};
1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?