node.js - Promise 循环中的操作函数不起作用

标签 node.js promise bluebird

已关注 this关于 stackoverflow 的问题,我尝试使 promiseFor 方法工作但没有成功。由于我没有足够的“声誉”来评论该帖子,所以我就在这里。这是递归循环:

var promiseFor = Promise.method(function(condition, action, value) {
  if (!condition(value)) return value;
  return action(value).then(promiseFor.bind(null, condition, action));
});

这就是我测试它的方式:

promiseFor(function(arr){   //condition
  return arr.length < 3;
}, function(arr){           //action
  arr.push(arr.length+1);
  return arr;
}, [])                      //initial value
.done(function(arr){
  console.log(arr);
});

我期望得到 [1,2,3] 的输出。但相反,我得到了一个指向该行的 TypeError: undefined is not a function :

  return action(value).then(promiseFor.bind(null, condition, action));

这恰好是我还没有完全理解的一行。 promiseFor.bind(null, condition, action) 到底是做什么的?

编辑: 感谢 kyrylkov,我已将 action 更改为:

function(arr){
  return new Promise(function(resolve){
    arr.push(arr.length + 1);
    resolve(arr);
  });
}

现在工作起来很有魅力。

最佳答案

在您的测试中,action(封装在 Promise.method 中的匿名函数中的第二个参数)是一个返回数组而不是 Promise 的函数:

function(arr){
  arr.push(arr.length+1);
  return arr;
}

因此,您在调用 action(value).then 时收到错误,因为该数组没有 then 方法。

关于node.js - Promise 循环中的操作函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31863593/

相关文章:

javascript - promise 的 MongoDB Node 驱动程序 .forEach() 返回什么样的 promise ?

javascript - React/Redux - 调度方法 - 返回错误

node.js - 试图了解 promisification 如何与 BlueBird 一起工作

node.js - 如何在 app.js 中使用 LUIS 来识别不同文件夹中的对话框

javascript - 避免带有 promise 的嵌套回调

javascript - 以处理错误的方式启动 javascript Promise Bluebird 链

javascript - NodeJS Bluebird Promise 在处理程序中创建,但未从处理程序返回

node.js - SSE - 服务器发送的事件 - 如何重用相同的 EventSource

javascript - 无法删除来自 Cassandra 数据库的 rows.__columns 属性

javascript - 我可以在 ES6 的生产环境中使用 Babel Require Hook 吗?