Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9054

【Node.js】promiseの使い方

$
0
0

プログラミング勉強日記

2021年2月28日

基本的な書き方

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

returnnewPromise(resolve){// 処理を記述する}
具体例
functionmyFunction(){returnnewPromise(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を利用できる。

functionmyFunction(){returnnewPromise(function(resolve,reject){reject(newError("エラーが発生しました"));})}
myPromise().then(function(data){console.log(data);},function(error){console.log(error.message);})
実行結果
エラーが発生しました

参考文献

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


Viewing all articles
Browse latest Browse all 9054

Latest Images

Trending Articles