Help us understand the problem. What is going on with this article?

Promiseで複数の非同期処理を書く(Node v4以降、ライブラリなし)

More than 3 years have passed since last update.

目的

例えばファイル読み込み、SQL発行、HTTPリクエスト、とか順序だててやらないといけない時、複数の非同期処理をネストしたコールバックから置き換える

環境

node v4~(v4.3.2 or v5.0.0で確認)

コールバック(書き換え前)

callback.js
var fs = require('fs');

console.log('readFile ---- start.');
fs.readFile('a.txt', function(err, data){
    console.log('readFile ---- a.txt data : '+data);
    fs.readFile('b.txt', function(err, data){
        console.log('readFile ---- b.txt data : '+data);
        fs.readFile('c.txt', function(err, data){
            console.log('readFile ---- c.txt data : '+data);
        });
    });
});
$ node callback.js
readFile ---- start.
readFile ---- a.txt data : a.txtの内容
readFile ---- b.txt data : b.txtの内容
readFile ---- c.txt data : c.txtの内容

Promise(書き換え後)

promise.js
'use strict'

const fs = require('fs');

new Promise((resolve, reject)=>{
    console.log('Promise ---- start.');
    fs.readFile('a.txt', (err, data)=>{
        !err ? resolve(data) : reject(err);
    });
}).then((result)=>{
    console.log('Promise ---- a.txt result : '+result);
    return new Promise((resolve, reject)=>{
        fs.readFile('b.txt', (err, data)=>{
            !err ? resolve(data) : reject(err);
        });
    })
}).then((result)=>{
    console.log('Promise ---- b.txt result : '+result);
    return new Promise((resolve, reject)=>{
        fs.readFile('c.txt', (err, data)=>{
            !err ? resolve(data) : reject(err);
        });
    })
}).then((result)=>{
    console.log('Promise ---- c.txt result : '+result);
},(err, hoge)=>{
    console.log('Promise ---- err : '+err+' hoge:'+hoge);
});

$ node promise.js
Promise ---- start.
Promise ---- a.txt result : a.txtの内容
Promise ---- b.txt result : b.txtの内容
Promise ---- c.txt result : c.txtの内容

層が深くなればなるほどPromiseのが見やすくなる
ライブラリに依存したくない場合はこんな感じで書くつもり

natsuki_summer
Webとかネイティブアプリのエンジニアのメモ書き 基本勉強用です
https://nyamanaka.com/
binc
Eコマースプラットフォーム「BASE」、オンライン決済サービス「PAY.JP」、購入者向けID型決済サービス「PAY ID」の3つのサービスを運営しています。
https://binc.jp
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした