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都是只在声明所在的块级作用域内有效。

 

 

 

你可能感兴趣的:(ES6)