Promises,将额外的参数传递给 then chain

编程入门 行业动态 更新时间:2024-10-26 19:40:19
本文介绍了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屋!

更多推荐

[db:关键词]

本文发布于:2023-03-30 02:59:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/768645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:参数   Promises   chain

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!