javascript - 从 Promise 返回非返回函数导致警告

标签 javascript node.js express promise sequelize.js

我有一个nodejs Express应用程序,我使用一个库,该库具有用于执行函数的典型回调接口(interface)。我的持久层使用基于 promise 的方法。我有以下代码让我困扰

getUserByName('dave')
  .then(function (user) {
    // check stuff and call the callback with success
    return cb(null, true);
  })
  .catch((err) => cb(err, false));

问题:cb(null, true) 函数返回 undefined,并且 Promise 以此警告结束在处理程序中创建了一个 Promise,但并未从中返回

我可以通过运行回调来修复此问题,然后像这样返回 null:

    // check stuff and call the callback with success
    cb(null, true);
    return null;

但现在我问自己真的是在等待回调完成吗?这是处理此类警告的正确方法吗?我感觉我做错了。

我记得在编写快速中间件时遇到了同样的问题,然后在 Promise 中调用 next() 函数跳转到下一个中​​间件。它还返回未定义。有什么建议来处理这个问题吗?

最佳答案

嗯,正确的解决方案当然是切换到不使用 Node 式回调并利用 Promise 的框架,这样您就可以简单地返回您的 Promise,而无需调用传递给您的任何回调。

如果这是不可能的,您仍然不应该从正常代码中调用此类回调。警告是正确的,您正在调用一些执行更多异步工作(创建其他 promise )的东西(回调),但没有将其返回到您的链中(“忘记”等待它),这是一个常见的错误。您的显式 return null 可以正确抑制此警告,但实际上有更好的方法:
编写代码就像您已经返回 Promise 一样,然后调用 .asCallback专门用于此目的(包括不发出警告):

getUserByName('dave')
  .then(function (user) {
    // check stuff and call the callback with success
    return true;
  })
  .asCallback(cb)

关于javascript - 从 Promise 返回非返回函数导致警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763388/

相关文章:

javascript - myeclipse中如何实现文本换行?

node.js - 在node.jsexpress中,对 '/locations/search'的请求总是到达 '/locations/:location_id',如何以正确的方式路由

javascript - 如何从 Electron 的渲染器中获取 Node 模块?

javascript - 将一个大整数编码为 base62

javascript - Chrome 中快速挂 AJAX 删除后

javascript - Angular 数据表中括号内数字的排序

javascript - knockout JS : Checking if items in nested sortable were reordered

javascript - jQuery 获取 <对象> html

node.js - 具有 jwt 授权的 get 方法返回空对象,我们是否需要解码 jwt token ?

javascript - 一种型号的两个版本