You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//badnewPromise((resolve,reject)=>{resolve()}).then(data=>{thrownewError('Something wrong!')},err=>{console.log(err)})//Uncaught (in promise) Error: Something wrong!// at Promise.then.data// goodnewPromise((resolve,reject)=>{resolve()}).then(data=>{thrownewError('Something wrong!')}).catch(err=>{console.log(err)});//Error: Something wrong!// at Promise.then.data// goodnewPromise((resolve,reject)=>{thrownewError('reject')}).then(data=>{thrownewError('Something wrong!')}).catch(err=>{console.log(err)});//Error: reject// at Promise (<anonymous>:1:42)// at new Promise (<anonymous>)// at <anonymous>:1:1
上面一种写法捕获不到 then 方法的异常,下面的写法在最外层加 catch 能够捕获 promise 中冒泡的异常,也能捕获 then 的异常
Catch 无法捕获异步的异常
Promise.resolve().then(_=>{setTimeout(()=>{thrownewError('the err can not catch');},1000);}).catch(err=>console.log(err))// Uncaught Error: the err can not catch// at setTimeout (<anonymous>:4:13)
constpromises=[1,2,3].map(function(el){returnnewPromise(resolve=>{//为了测试看效果而加的同步阻塞letsum=0for(leti=0;i<9999999;i++){sum++}returnresolve(el)})});Promise.all(promises).then(data=>{// data = [1,2,3]console.log(data)}).catch(err=>console.log(err))
Promise
then( ) 函数返回值
返回 Promise 对象,被下一个 then() 捕获
返回的同步值,被 Promise.resolve() 方法转换
Catch
为什么不建议写 then 的第二个参数而使用 catch ?
上面一种写法捕获不到 then 方法的异常,下面的写法在最外层加 catch 能够捕获 promise 中冒泡的异常,也能捕获 then 的异常
Catch 无法捕获异步的异常
Promise 串行
等价于
Promise 并行
References
The text was updated successfully, but these errors were encountered: