承诺,通过附加参数,然后链 [英] Promises, pass additional parameters to then chain

查看:171
本文介绍了承诺,通过附加参数,然后链的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

承诺,例如

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

我们在promise后调用方法:

After we call then method on promise:

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

doWork功能如下所示:

doWork function looks like this:

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

如何避免doWork中的内部函数,以获取从承诺和文本参数访问数据?如果有什么技巧?谢谢。

how can i avoid inner function in doWork, to get access to data from promise and text parameter? if there any tricks? thanks.

推荐答案

您可以使用 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 到,

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

现在,文本将在 doWork 数据中实际'text'作为承诺解决的价值。

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);

这篇关于承诺,通过附加参数,然后链的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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