所以我不知道如何转换我同步构建但使用异步调用的函数。
greyColor
我不确定如何在完成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()
答案 0 :(得分: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();
};
答案 1 :(得分:0)
您可以使用已经为Promisified版本提供帮助的第三方开源工具!一项Google搜索显示:https://www.npmjs.com/package/fs-promise
否则,您可以使用https://stackoverflow.com/a/34642827/3814251中的提示自行宣传该方法。
(或者,使用您在自己的答案中发布的回调。)