javascript - promise : how to pass function with parameters?

标签 javascript node.js es6-promise

在下面的测试代码中,我尝试将带有参数(即 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));

最佳答案

只需传递函数名称即可:

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>高阶函数返回函数,以便您可以在.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));

关于javascript - promise : how to pass function with parameters?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51690100/

相关文章:

javascript - Node.js 应用程序崩溃

javascript - AngularJS 中算术运算符的问题

node.js - 优雅地关闭nodejs工作线程

node.js - 使用 Node db-migrate 在事务中禁用包装迁移

javascript - 在 chrome.runtime 消息系统中使用 promises

javascript - 将回调转换为 Promise 时出现问题

promise - 最佳实践 : Promises reject/throw

javascript - 使用 javascript 和 jQuery,解析以查找然后在 html 文档中找到时删除 <p></p>

javascript - 如何处理 Cognito Web 应用程序 session 刷新?

javascript - Wordpress 使用 URL 注销并重定向到指定页面