如何使超级代理兑现承诺

用户名

我一直在学习Node / Javascript,从一开始就使用诺言(我不知道如何使用诺言,而且常常想知道如果没有诺言,其他人将如何相处)。

所以有时我需要“简单化”一些简单的内容,例如使用读取文件fs

var readFile = function(path) {
    return new Promise(function(fulfill, reject) {
        fs.readFile(path, function(err, data) {
            if (err) { reject(err); }
            else { fulfill(data); }
        });
    });
};

这一直很好。现在我需要对进行相同的操作superagent,但是它使用的链接样式使我陷入困境。

var request = require('superagent');
request.get(...).set(...).set(...).end(callback);  // stuck!

我想end()用一个返回诺言方法替换该方法(或忽略它并添加一个新方法)。像这样

var endQ = function() {
    return new Promise(function(fulfill, reject) {
        this.end(function(err, res) {     // "this" is the problem!
            if (err) { reject(err); }
            else { fulfill(res); }
        });
    });
};

// then I could say this:
request.get(...).set(...).set(...).endQ().then(function(res) {
    // happiness
}).catch(function(err) {
    // sad about the error, but so happy about the promise!
});

这个问题在向对象添加方法方面有各种各样的建议,但是很难确定到底是什么。这个答案让我特别担心许多建议围绕着从对象的“类”开始,然后将功能添加到中.prototype像这样...

// this part doesn't make sense
var requestInstance = new Request();   // no such thing in request as far as I know
requestInstance.prototype.endQ = endQ; // would be great, but no

看到我的问题了吗?我希望JS等效于“子类化”请求“类”并添加一个方法,但是由于它是一个模块,因此我需要将请求类视为或多或少不透明。

本杰明·格伦鲍姆(Benjamin Gruenbaum)

首先,超级代理已经支持诺言

request.get(...).set(...).set(...).then(response => {
    // handle it here
});

请注意,与常规不同thenthen这里不是一个承诺-它实际上是调用请求并延迟执行。

其次,您要执行的操作非常简单:

Object.getPrototypeOf(request.get(...)).endQ = function() { // get to prototype and define
  /* your code here */
};

这是superagent本身的作用:

exports.then = function then(resolve, reject) {
  if (!this._fullfilledPromise) {
    var self = this;
    this._fullfilledPromise = new Promise(function(innerResolve, innerReject){
      self.end(function(err, res){
        if (err) innerReject(err); else innerResolve(res);
      });
    });
  }
  return this._fullfilledPromise.then(resolve, reject);
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章