UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝ID:1):3

时间:2017-06-17 12:32:35

标签: javascript typescript

declare var Promise: any;
function all(promises : Array<Promise<any>>) : Promise<Array<any>> {
return new Promise( (resolve, reject) => {
    if(promises.length===0){
        resolve([]);
    }
    else{
        promises[0].then((result)=>{
        all(promises.slice(1)).then(rest=>{resolve([result].concat(rest))}).catch((err)=>{reject(err)})
        }).catch((err)=>{reject(err)});
    }
});
}
//Test
function p1() { // always succeeds, with content 1
return new Promise((resolve, reject) => {
    setTimeout(() => { resolve(1); }, Math.random() * 1000);
});
}
function p3() { // always fails, with err 3
return new Promise((resolve, reject) => {
    setTimeout(() => { reject(3); }, Math.random() * 1000);
});
}
all([p1(),p3()])
.then(content => { console.log("Test 2 Failed: ", content); })
.catch(err => {
        if (err === 3) console.log("Test 2 Succeeded: ", err);
        else console.log("Test 2 Failed: ", err); 
    }
);

运行此代码时出现此错误

  

(node:12624)UnhandledPromiseRejectionWarning:未处理的promise promise(拒绝ID:1):3(node:12624)DeprecationWarning:不推荐使用未处理的promise promise。将来,未处理的承诺拒绝将使用非零退出代码终止Node.js进程。测试2成功:3(节点:12624)PromiseRejectionHandledWarning:异步处理承诺拒绝(拒绝ID:1)

所以请帮我解决一下!

0 个答案:

没有答案