【问题标题】:How to call "apply" in a promise-based setup in Javascript to pass parameters to the next then()?如何在 Javascript 中基于 Promise 的设置中调用“apply”以将参数传递给下一个 then()?
【发布时间】:2014-07-08 07:46:08
【问题描述】:

我正在编写一个基于 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 来回传arguments 而不是array。所以我可以在我的承诺链中添加另一个步骤并执行:

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

与:

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

问题: 但是由于我无法访问“下一个”回调方法,所以我不能apply。有没有办法将参数列表而不是数组发送回下一步?

【问题讨论】:

    标签: javascript arrays arguments promise rsvp.js


    【解决方案1】:

    这通常称为.spread,在ES6 中通过解构将是available natively。所以目前行不通的最优解是:

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

    RSVP 承诺目前不支持开箱即用的spread,但是对于 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
    });
    

    【讨论】:

    • 啊。看起来不错。非常感谢。
    猜你喜欢
    • 2018-06-05
    • 2020-02-23
    • 2018-08-13
    • 2020-06-13
    • 1970-01-01
    • 2014-09-17
    • 1970-01-01
    • 1970-01-01
    • 2014-07-13
    相关资源
    最近更新 更多