Terry Cho
Terry Cho

Reputation: 618

node.js promise sequence

During testing node.js promise framework. I got a strange result. here is a code.

var Promise = require('promise');

var fs = require('fs');
var src = '/tmp/myfile.txt';
var des = '/tmp/myfile_promise2.txt';

var fread = Promise.denodeify(fs.readFile);
var fwrite = Promise.denodeify(fs.writeFile);

fread(src)
        .then(
            function(text){
                console.log('Read done');
                return fwrite(des,text);
            })
        .then(console.log('Write done'))
        .catch(function(reason){
            console.log('Read or Write file error');
            console.log(reason);
        });

File is successfully written. But console output is like below

Write done
Read done

My expected result is, print "Read done" first and then "Write done". What was wrong?

Upvotes: 0

Views: 117

Answers (1)

Terry Cho
Terry Cho

Reputation: 618

Thanx @E_net4 ^ @Joachim Isakkson

After wrapping it with function, it works. I need to learn promise creation life cycle again.

var Promise = require('promise');

var fs = require('fs');
var src = '/tmp/myfile.txt';
var des = '/tmp2/myfile_promise2.txt';

var fread = Promise.denodeify(fs.readFile);
var fwrite = Promise.denodeify(fs.writeFile);

fread(src)
.then(
        function(text){
            console.log('Read done');
            return fwrite(des,text); // 체이닝을 하려면 return을 해줘야 함. 
        })
        .then(function(){
            console.log('Write done');
        })
        .catch(function(reason){
            console.log('Read or Write file error');
            console.log(reason);
        });

Upvotes: 3

Related Questions