JavaScript基本功之promise

promise的状态和变化

状态

  • pending: 进行中
  • resolved: 成功
  • rejected: 失败

状态变化

  • pending-resolved =》then回调方法1
  • pending-reject =》then回调方法2(优先级更高) 或 catch方法

then-error和catch哪个先执行?

结论:

  • 测试发现只会执行一个,优先执行onerror
  • Promise.prototype.catch是Promise.prototype.then(null, rejection)的别名
// 定义 promise
function test(){
   
    
    
  return new Promise((_,reject)=>{
   
    
    
    // 已知错误和异常错误 2种情形结果一样
    return reject('程序错误') // "程序错误"
    // return a.push(1)  // ReferenceError: a is not defined
  })
}

// 测试
test().then(data=>{
   
    
     // 只有then-error
  console.log('data=',data)
},error=>{
   
    
    
  console.error('then error=',error)
})
// 结果: then error= 程序错误

test().then(data=>{
   
    
     // 只有catch
  console.log('data=',data)
}).catch(error=>{
   
    
    
  console.error('catch error=',error)
})
// 结果: catch error= 程序错误

test().then(data=>{
   
    
     // 既有then-error又有catch
  console.log('data=',data)
},error=>{
   
    
    
  console.error('then error=',error)
}).catch(error=>{
   
    
    
  console.error('catch error=',error)
})
// 结果: then error= 程序错误

then-error和catch适用场景?

个人想法:

  • 如果有多个promise链式调用,采用catch更为方便,
  • 如果只有1个promise调用都可以
// 链式调用
Promise.resolve(1).then((data)=>{
   
    
    
    console.log('data: ',data);
    return 2;
}).then((data)=>{
   
    
    
    console.log('data: ',data);
    return 3;    
}).then((data)=>{
   
    
    
    console.log('data: ',data);
    return 4;    
}).then((data)=>{
   
    
    
    console.log('data: ',data);
    // a.push('hi'); // 程序性异常 a未定义 
    return Promise.reject('程序错误');  // 自定义异常
}).then((data)

猜你喜欢

转载自blog.csdn.net/qubes/article/details/134344894