简体   繁体   English

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

[英]Promises, pass additional parameters to then chain

A promise, just for example:一个承诺,例如:

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

After we call the .then() method on the promise:在我们对.then()调用.then()方法之后:

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

Then doWork function looks like this:然后doWork函数看起来像这样:

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

How can I avoid returning an inner function in doWork, to get access to data from the promise and text parameters?如何避免在 doWork 中返回内部函数,以从 promise 和 text 参数访问数据? Are there any tricks to avoiding the inner function?有什么技巧可以避免内部函数吗?

Perhaps the most straightforward answer is:也许最直接的答案是:

P.then(function(data) { return doWork('text', data); });

Or, since this is tagged ecmascript-6 , using arrow functions:或者,因为它被标记为ecmascript-6 ,所以使用箭头函数:

P.then(data => doWork('text', data));

I find this most readable, and not too much to write.我觉得这最易读,而且不会写太多。

You can use Function.prototype.bind to create a new function with a value passed to its first argument, like this您可以使用Function.prototype.bind创建一个新函数,并将值传递给它的第一个参数,如下所示

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

and you can change doWork to,你可以将doWork更改为,

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

Now, text will be actually 'text' in doWork and data will be the value resolved by the Promise.现在, text实际上是doWork 'text'data将是 Promise 解析的值。

Note: Please make sure that you attach a rejection handler to your promise chain.注意:请确保您将拒绝处理程序附加到您的承诺链。


Working program: Live copy on Babel's REPL工作程序: 实时复制 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);

Use currying.使用柯里化。

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

var curriedDoWork = function(text) {
    return function(data) {
        console.log(data + text);
    }
};

P.then(curriedDoWork('text'))
.catch(
    //some error handling
);

Lodash offers a nice alternative for this exact thing. Lodash 为这个确切的东西提供了一个不错的选择。

 P.then(_.bind(doWork, 'myArgString', _));

 //Say the promise was fulfilled with the string 'promiseResults'

 function doWork(text, data) {
     console.log(text + " foo " + data);
     //myArgString foo promiseResults
 }

Or, if you'd like your success function to have only one parameter (the fulfilled promise results), you can utilize it this way:或者,如果您希望成功函数只有一个参数(履行的承诺结果),您可以这样使用它:

P.then(_.bind(doWork, {text: 'myArgString'}));

function doWork(data) {
    console.log(data + " foo " + this.text);
    //promiseResults foo myArgString
}

This will attach text: 'myArgString' to the this context within the function.这会将text: 'myArgString'附加到函数内的this上下文。

The new answer to this question is to use arrow functions (which automatically bind the this and are much more readable) .这个问题的新答案是使用箭头函数(它会自动绑定this并且更具可读性) Google for links such as: https://2ality.com/2016/02/arrow-functions-vs-bind.html谷歌链接,如: https : //2ality.com/2016/02/arrow-functions-vs-bind.html

You can set the text like:您可以将文本设置为:

this.text = 'text';
P.then(data => doWork(data));

Note: this.text inside doWork will evaluate to 'text'.注: this.textdoWork将评估为“文本”。

This is suggested by jib above and that (or this!) should be the accepted answer now.这是上面的 jib 建议的,现在(或这个!)应该是公认的答案。

use this so you can access global variable inside the promise body使用它,以便您可以访问承诺正文中的全局变量

var ref=this;

Example例子

p.then((data)=>{
  var ref=this;
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM