javascript - 未处理的PromiseRejection警告: TypeError: Cannot read property 'length' of undefined

标签 javascript node.js backend

(node:55028) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined at /Users/patrickstanciu/WebstormProjects/autismassistant/backend/api/controllers/paymentsController.js:1045:34
at processTicksAndRejections (internal/process/task_queues.js:94:5) (node:55028) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:55028) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

当我尝试使用用户登录时,我的 node.js 后端出现此错误。为什么会出现? 这是行:

   if (!profilePromise.rows.length) {
            resolve({
                success: true,
                cardDetails: null,
                planId: null
            })
            return;
        }

我对上面的“长度”有疑问

最佳答案

根据名称,profilePromise 是一个 promise 。 Promise 没有 rows 属性,因此 profilePromise.rowsundefined 并且您无法从 undefined< 读取任何属性.

您需要使用 promise 并使用其履行值,我猜这是具有length属性的东西:

profilePromise
.then(rows => {
    if (rows.length) {
        resolve(/*...*/);
    }
})
.catch(error => {
    // ...handle/report the error...
    // Probably `reject` here?
});

有关使用 promise 的更多信息 here .

<小时/>

旁注:假设我是对的,profilePromise 确实是一个 promise ,这表明这段代码正在成为 the explicit promise creation antipattern 的牺牲品。 。不要创建自己的 Promise,然后调用 resolvereject,而是链接到现有的 Promise:

return profilePromise
    .then(rows => {
        if (rows.length) {
            return {
                success: true,
                cardDetails: null,
                planId: null
            };
        }
        // Either return something else here, or `throw` if `rows` not having
        // a truthy `length` is an error
    });

关于javascript - 未处理的PromiseRejection警告: TypeError: Cannot read property 'length' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60175036/

相关文章:

javascript - 显示在 ReactJS 中显示模态的按钮列表

javascript - 使用 html2canvas 提交时从表单创建屏幕截图

javascript - 在本地存储上保存背景颜色

windows - 如何在 Windows 上刷新 console.log 输出

node.js - 是否可以在 URL 中不显示端口号的情况下使用 Node.js 服务器。

node.js - 计算线性渐变的颜色

javascript - Backbone.Models this.get() 是复制整个数组还是指向内存中的同一个数组

javascript - 在客户端和nodejs服务器上使用静态javascript文件

swift - Vapor 4 : Children relation not eager loaded, 使用 $ 前缀访问

android - 我可以使用购买状态 API 来验证应用程序是否是通过 Play 商店购买的吗