节点原型和异步

Node Prototypes and Async

本文关键字:异步 原型 节点      更新时间:2023-09-26

当我调用log()时,我如何在read()中返回异步函数的值?我知道代码可能不是100%正确,但我希望你能理解。我用谷歌搜索了一下,但还是有点困惑。希望有人能帮我。

function Whatever(directory) {
  this.source = 'someDir';
}
Whatever.prototype.read = function (dir) {
  dir = dir || this.source;
  recursive(dir, ['.*'], function (err, files) {
    if (err) throw err;
    return files;
  });
};
Whatever.prototype.log = function() {
  console.log(this.read());
};

您可以向read函数添加回调,与递归函数相同,例如:

Whatever.prototype.read = function (dir, callback) {
    dir = dir || this.source;
    recursive(dir, ['.*'], callback);
};

然后将错误检查和用法放入日志函数中:

Whatever.prototype.log = function() {
    this.read(function(err, files){
        if(err){ throw err; }
        console.log(files);
    });
};

网上有很多更详细地解释回调的链接,你应该调查一下。然而,一旦你掌握了这些,我建议你阅读有关承诺的内容,因为它们更容易处理。