【问题标题】:Promise: how to pass function with parameters? [duplicate]Promise:如何传递带参数的函数? [复制]
【发布时间】:2019-01-12 09:05:18
【问题描述】:

在下面的测试代码中,我尝试将带有参数(即 t2、t3)的预定义函数传递给 then。但它抱怨“r”未定义。

var Promise = require('bluebird');

var t2 = function(r) {
    console.log("2r: " + r);
    return 2 * r;
};

var t3 = function(r) {
    console.log("3r: " + r);
    return 3 * r;
};

new Promise(function(resolve, reject) {

    setTimeout(function() {
        resolve(1);
        reject(2)
    }, 1000);
})
.then(t2(r), t3(r))
.then(t2(r), t3(r))
.then(t2(r), t3(r));

【问题讨论】:

    标签: javascript node.js es6-promise


    【解决方案1】:

    只需传递函数名称即可:

    var t2 = function(r) {
      console.log("2r: " + r);
      return 2 * r;
    };
    
    var t3 = function(r) {
      console.log("3r: " + r);
      return 3 * r;
    };
    
    new Promise(function(resolve, reject) {
    
        setTimeout(function() {
          resolve(1);
          reject(2)
        }, 1000); // (*)
    
      })
      .then(t2, t3)
      .then(t2, t3)
      .then(t2, t3);

    如果你实际上想要传递额外的参数你事先知道,让t2t3高阶函数return 函数,以便您可以在 .then 的参数列表中调用:

    var t2 = extra => r => {
      console.log("2r: " + r);
      console.log('extra param: ' + extra);
      return 2 * r;
    };
    
    var t3 = extra => r => {
      console.log("3r: " + r);
      console.log('extra param: ' + extra);
      return 3 * r;
    };
    
    
    const r = 'foo';
    new Promise(function(resolve, reject) {
    
        setTimeout(function() {
          resolve(1);
          reject(2)
        }, 1000); // (*)
    
      })
      .then(t2(r), t3(r))
      .then(t2(r), t3(r))
      .then(t2(r), t3(r));

    【讨论】:

      【解决方案2】:

      您没有将r 传递给函数。 .then 将值传递给回调。

      new Promise(function (resolve, reject) {
        setTimeout(function () {
          resolve(1)
          reject(2)
        })
      })
      .then((r) => /* do stuff with r here */)
      

      如果您需要注销结果,您会得到类似.then((r) => { t2(r); t3(r); }) 的信息。如果您只需要返回乘法函数(或其他)的结果,.then(t2) 将起作用(对于一个函数)。请注意,我在这里使用箭头函数;它们现在可以在 Node 和大多数浏览器中使用,但如果需要,您可以使用 function 关键字。

      你在这里也奇怪地使用了逗号运算符——记住,它基本上与有一个语句和 then 一个返回相同,因为你的函数不执行任何突变(只是log 副作用),您实际上不会使用每个 .then 中的第一个函数影响任何数据。

      【讨论】:

        猜你喜欢
        • 2020-02-21
        • 2015-11-08
        • 2016-05-20
        • 1970-01-01
        • 2020-01-06
        • 1970-01-01
        • 1970-01-01
        • 2012-12-21
        • 2012-12-11
        相关资源
        最近更新 更多