用于处理带有promise的外部接口中的参数的设计模式

Design Pattern for handling arguments in external interfaces with promises

本文关键字:接口 参数 设计模式 外部 用于 promise 处理      更新时间:2024-03-03

假设我有一个函数,在其中我访问一个无法更改的接口(在本例中为mongoose)。该接口返回一个promise,该promise只是传入找到的资源;

show = function(response) {
  Resource.findById(req.params.id).then(renderResource);
}
function renderResource(resource) {
  // render the response
}

为了呈现响应,我需要访问show函数中的response参数。我可以使用bind函数,劫持this作为响应变量;

show = function(response) {
  Resource.findById(req.params.id).then(renderResource.bind(response));
}
function renderResource(resource) {
  this.send(resource);
}

但是,如果我想将另一个参数传递到renderResource函数中,该怎么办?我唯一能做到的就是这样;

show = function(response) {
  Resource.findById(req.params.id).then(function(resource) {
    renderResource.call(response, resource, "foo"));
  }
}
function renderResource(resource, otherArg) {
  this.send(resource);
  //do something with otherArg
}

但在这一点上,我不再对代码感到满意,因为;

  • 我不得不声明一个函数文本,并且正在回调地狱
  • 我纯粹使用call,所以我仍然可以在函数中使用this,但实际上,到目前为止,我还不如将response作为第三个arg传入

我确信,必须有一种模式或某种东西来以更整洁的方式处理这个问题,而不必声明新的函数文本。有人能提出一个模式吗?有没有一种更整洁的方法来处理这种情况?

您可以根据需要向bind传递任意多个参数。我会避免使用this作为传递参数的方式,以避免混淆。

show = function(response) {
  Resource.findById(req.params.id)
    .then(renderResource.bind(null, response, "foo"));
}
function renderResource(response, otherArg, resource) {
  response.send(resource);
  //do something with otherArg
}

有关详细信息,请参阅bind文档:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind

这被称为特殊应用程序:
https://en.wikipedia.org/wiki/Partial_application