Promises,将额外的参数传递给 then chain [英] Promises, pass additional parameters to then chain

查看:16
本文介绍了Promises,将额外的参数传递给 then chain的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个承诺,例如:

var P = new Promise(function (resolve, reject) {
  var a = 5;
  if (a) {
    setTimeout(function(){
      resolve(a);
    }, 3000);
  } else {
    reject(a);
  }
});

在我们对 promise 调用 .then() 方法之后:

After we call the .then() method on the promise:

P.then(doWork('text'));

然后 doWork 函数看起来像这样:

Then doWork function looks like this:

function doWork(data) {
  return function(text) {
    // sample function to console log
    consoleToLog(data);
    consoleToLog(b);
  }
}

如何避免在 doWork 中返回内部函数,以访问来自 promise 和 text 参数的数据?有什么技巧可以避开内部函数吗?

How can I avoid returning an inner function in doWork, to get access to data from the promise and text parameters? Are there any tricks to avoiding the inner function?

推荐答案

您可以使用 Function.prototype.bind 来创建一个新函数,并将值传递给它的第一个参数,就像这样

You can use Function.prototype.bind to create a new function with a value passed to its first argument, like this

P.then(doWork.bind(null, 'text'))

并且您可以将 doWork 更改为,

and you can change doWork to,

function doWork(text, data) {
  consoleToLog(data);
}

现在,text 实际上是 doWork 中的 'text' 并且 data 将是被解析的值承诺.

Now, text will be actually 'text' in doWork and data will be the value resolved by the Promise.

注意:请确保您将拒绝处理程序附加到您的承诺链.

Note: Please make sure that you attach a rejection handler to your promise chain.

工作程序: Babel 的 REPL 上的实时副本

function doWork(text, data) {
  console.log(text + data + text);
}

new Promise(function (resolve, reject) {
    var a = 5;
    if (a) {
      setTimeout(function () {
        resolve(a);
      }, 3000);
    } else {
      reject(a);
    }
  })
  .then(doWork.bind(null, 'text'))
  .catch(console.error);

这篇关于Promises,将额外的参数传递给 then chain的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆