微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Javascript中基于承诺的设置中调用“应用”以将参数传递给下一个then()?

我正在写一个基于promise的方法,该方法采用一个参数并在下一步中返回一个值数组.像这样:

foo(a).then(function (arr) {});

在我的方法foo中,我正在执行以下操作:

foo = function (a) {

  ...

  // this will return my array
  function returnArray(my_return_array) {
    return RSVP.all(my_return_array).fail(console.log);
  }

  return requestBundleElements(a)
    .then(assembleReturnArray)
    .then(returnArray)
    .fail(console.log);
};

我想知道是否有可能通过调用apply来传递参数而不是数组.因此,我可以在我的诺言链中添加一个步骤并执行以下操作:

  return requestBundleList(setLoadingOrder(module_list))
    .then(assembleReturnArray)
    .then(returnArray)
    .then(returnArguments)
    .fail(console.log);

与:

  function returnArguments(my_result_array) {
     //... "apply" something here
  }

题:
但是由于我无权访问“下一个”回调方法,因此无法申请.有什么方法可以将参数列表而不是数组发送回下一步吗?

解决方法:

这通常称为.spread,在ES6中通过解构将为available natively.因此,目前不起作用的最佳解决方案是:

foo(a).then([a,b,c] => console.log(a,b,c); /* applied array to args */);

RSVP承诺目前不支持即开即用,但是对于Bluebird或Q,它看起来像:

foo(a).spread(function(a,b,c){
      // array ["a", "b", "c"] was applied into three parameters.
});

如果您有兴趣,可以将其自己添加到RSVP:

RSVP.Promise.prototype.spread = function(fn){
    return this.then(function(val){ // just like then
        return fn.apply(null, val); // only apply the value
    });
};

这可以让您做到:

RSVP.Promise.resolve([1, 2, 3, 4]).spread(function(one, two, three, four){
    console.log(one + two + three + four); // 10
});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐