Bluebird .then():未定义函数引用时没有TypeError

时间:2015-02-01 20:17:07

标签: javascript node.js promise bluebird

我最近开始使用承诺,并为我发现了一个奇怪的行为。 当我给.then()函数一个未定义函数的引用时,它就被跳过,然后调用它。

一个例子:

var cust = customer({general: { cust_id: 22 }}); // just for testing
req.pool.getConnectionAsync()
        .then(cust.del) // cust.del is 'undefined'
        .then(function(dbResult) { console.log("dbresult:"); console.log(dbResult);  res.status(200).end(); })
        .catch(function (e) { console.log(e); res.status(500).end(); });

所以这里发生了什么:

  • getConnectionAsync返回应该提供给cust.del
  • 的连接
  • cust.del未定义(我输错了正确的函数将是cust.delete)
  • 没有引发错误,而是使用getConnectionAsync的连接调用下一个.then函数作为" dbresult"
  • 最后一个函数的输出是连接对象,而不是db结果对象,状态200返回给客户端

如果我将代码更改为:

req.pool.getConnectionAsync()
        .then(function(conn) { cust.del(conn) }) // type error is raised
        .then(function(dbResult) { console.log("dbresult:"); console.log(dbResult); res.status(200).end(); })
        .catch(function (e) { console.log(e); res.status(500).end(); });

然后我得到预期的TypeError并调用catch函数。

这是预期的行为吗?或者我错过了什么来防止这种情况? .then(cust.del)显然是更干净的代码,但由于这个函数不可调用,所以应该有一个错误。

此致 菲尔

1 个答案:

答案 0 :(得分:0)

就像评论所说,这类似于:

Promise.resolve().then(undefined); // undefined is ignored here

它在Promises / A +规范中指定,它在每个promise实现中都以这种方式工作。理由是Promises / A +不必支持.catch方法,你可以这样做:

Promise.reject().then(null, function(err){ /* handle */ });

以及与现有库的互操作性。

相关问题