Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
5
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

@natsuki_summer

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

目的

例えばファイル読み込み、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のが見やすくなる
ライブラリに依存したくない場合はこんな感じで書くつもり

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
5
Help us understand the problem. What are the problem?