关于javascript:前端基础知识Promise

4次阅读

共计 863 个字符,预计需要花费 3 分钟才能阅读完成。

Promise 总共有三种状态,别离是 pending,resolved,rejected。

  1. 状态变动是 pending->resolved 或者 pending->rejected,且状态变动不可逆。
  2. pending 不会触发 then 或者 catch 回调函数,resolved 会触发 then 回调函数,rejected 会触发 catch 回调函数。
  3. then 失常返回 resolved,外面有报错返回 rejected;catch 失常返回 resolved,外面有报错返回 rejected。

面试题

// 第一题
Promise.resolve().then(() => {console.log(1) // 返回 resolved 状态的 promise,不执行 catch
}).catch(() => {console.log(2)
}).then(() => {console.log(3)// 返回 resolved 状态的 promise
})

后果为 1,3

// 第二题
Promise.resolve().then(() => {console.log(1)
    throw new Error('erro1') // 本来应返回 resolved 状态的 promise,但因为抛出异样,所以返回 rejected 状态的 promise,执行 catch
}).catch(() => {console.log(2) // 返回 resolved 状态的 promise,执行 then
}).then(() => {console.log(3) // 返回 resolved 状态的 promise
})

后果为 1,2,3

// 第三题
Promise.resolve().then(() => {console.log(1)
    throw new Error('erro1') // 本来应返回 resolved 状态的 promise,但因为抛出异样,返回 rejected 状态的 promise
}).catch(() => {console.log(2) // 返回 resolved 状态的 promise,不执行 catch
}).catch(() => {console.log(3)
})

后果为 1,2
正文完
 0