Promise的“Uncaught (in promise) …”错误

2019-05-2427275次阅读ES6javascript

先看码:

export function sendAuth( data ){
    return new Promise( (resolve,reject) =>{
        $.post(`${ajaxUrl}auth/sendphonemsg`,data,json=>{
            const {code,msg,data} = JSON.parse(json);
            if(code == 2001){
              return reject(msg);
            }
            resolve( data );
        });   
    });
}

如上方代码,当code===2001状态时,就会进入rejected失败状态。那么就会出现以下这种js报错,并且卡死阻止代码往下运行

原因是因为后续并没有跟随任何then | catch语句,因此它将抛出错误,所以要养成良好习惯,promise记得写上catch

 

解决方案一catch语句:

export function sendAuth( data ){
    return new Promise( (resolve,reject) =>{
        $.post(`${ajaxUrl}auth/sendphonemsg`,data,json=>{ 
            const {code,msg,data} = JSON.parse(json);
            if(code == 2001){
              return reject(msg);
            }
            resolve( data );
        });
    }).catch(function(reason) {
         //有选择性的在此处抛出错误或不抛出
        //console.log('catch:', reason);
    });
}

 

解决方案二then语句:

export function sendAuth( data ){
    return new Promise( (resolve,reject) =>{
        $.post(`${ajaxUrl}auth/sendphonemsg`,data,json=>{
            const {code,msg,data} = JSON.parse(json);
            if(code == 2001){
                return reject(msg);
            }
            resolve( data );
        });
    }).then(function(data){
        //console.log(data);
    },function(reason){
        //有选择性的在此处抛出错误或不抛出
        //console.log('catch:', reason);
    });
}

 

解决方案三:

除非你不写reject(...)抛出异常,忽略rejected失败状态。就不会报错卡死JS。

上一篇: vue路由只更改参数后页面组件不更新问题  下一篇: 如何在没有try-catch块的情况下编写async await  

Promise的“Uncaught (in promise) …”错误相关文章