2016-12-25 55 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(); 
};