UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.

1. 出现问题

(node:2171) UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
    at getList (/Users/dr/Desktop/Project/nodeBlog/src/controller/blog.js:10:9)
    at handleBlogRouter (/Users/dr/Desktop/Project/nodeBlog/src/router/blog.js:18:30)
    at getPostData.then.postData (/Users/dr/Desktop/Project/nodeBlog/app.js:56:28)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:2171) 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:2171) [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.

2. 问题分析

(1)源码

const blogResult = handleBlogRouter(req, res);
        if(blogResult){
            blogResult.then(blogData => {
                res.end(
                    JSON.stringify(blogData)
                )
            })
            return
        }

(2) 原因

const blogResult = handleBlogRouter(req, res) 定义了变量且存在初始值,而const的值会随着传入参数的不同发生变化,所以发生了报错:TypeError: Assignment to constant variable.

3. 解决方法

将const 改为 let

4. const与let的比较

(1)区别:

  •         const一般是声明常量

          如const a=1,const声明的变量不得改变值,这意味着,const一旦声明变量,就必须立即初始化,不能留到以后赋值。如const a这样会报错

  •        let声明的变量可以改变,值和类型都可以改变,没有限制。
  •        const定义变量必须赋初始值,let不需要赋初始值

(2)共同点:

  • let与const都是只在声明所在的块级作用域内有效。

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值