2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

プログラミング勉強日記

2021年2月28日

基本的な書き方

 promise処理を作るには任意の関数の中でnew Promise()を返すのが基本となる。

return new Promise(resolve) {
    // 処理を記述する
}
具体例
function myFunction() {
  return new Promise(function (resolve) {
      resolve("Hello World");
  })
}

thenを使ったメソッドチェーン

 promiseによる非同期処理の結果を取得するにはthenを使ったメソッドチェーンを使用することができる。

// dataにpromiseの結果が格納されている
// resolve()に設定した文字列になる
myFunction().then(function(data) { console.log(data) })
実行結果
Hello World

promiseの並列処理

 allメソッドとraceメソッドを使った方法がある。
 allメソッドは、違うpromise処理が記述された関数をまとめて実行して、すべての結果が得られたタイミングでthenを実行できるようにする。なので、複数のpromise処理の結果をまとめて取得したい場合に向いてる。
 raceメソッドも複数のpromise処理を実行できるが、最初に結果が得られたpromiseの結果だけをthenメソッドで取得できる。

エラーハンドリング

 promiseの引数には結果を格納するresolveだけではなく、エラー情報を格納するrejectを利用できる。

function myFunction() {
  return new Promise(function (resolve, reject) {
      reject(new Error("エラーが発生しました"));
  })
}
myPromise()
  .then(function(data) {
    console.log(data);
  }, function(error) {
    console.log(error.message);
  })
実行結果
エラーが発生しました

参考文献

非同期処理:コールバック/Promise/Async Function
【node.js入門】Promiseによる非同期処理の使い方まとめ!

2
1
0

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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?