2016-12-25 79 views
0

所以我不知道如何轉換我有同步構建但使用異步調用的函數。nodejs的異步函數如何?

do_thing =() => { 
    var N = new Thing(); //sync 

    N.do_that();  // calls fs.readFile() and does some stuff with data :async 
    this.array.push(N); // sync but does not affect anything 
    this.save();  // calls fs.writeFile() but needs info from N that is not created yet as N.do_that() is not done 
} 

我不知道如何使它所以當N.do_that()完成它,然後調用this.save()。我不想使用fs.readFileSync()fs.writeFileSync()。我想知道如何像這樣:

N.do_that().then(this.save()); 

回答

0

好吧,我想通了。在我的N.do_that()裏面;我添加了一個回調,像這樣:

do_that = (callback) => { 
    fs.readFile("file", (err, fd) => { 
    // do stuff with fd 

    callback(); 
    return; 

    }); 
} 

然後,而不是調用:

N.do_that(); 
array.push(N); 
this.save(); 

我做

N.do_that(() => { 
    array.push(N); 
    this.save(); 
};