@jsongao98
2021-04-24T12:14:08.000000Z
字数 3315
阅读 180
JavaScript
new Promise被创建时,内部executor就自动执行,executor接受两个函数参数,resolve和reject
Promise.resolve().then(() => {//p1
console.log(0);
return new Promise.resolve(4);})
//p2,p2的状态和参数会传给p1.then中回调函数返回的promise
//如果 p2 是整数/字符串,则执行 FulfillPromise,直接改变 p1 的状态和结果
//但这里p2是一个fulfilled的promise,引擎内部的执行大致相当于 JS 代码:p1 = p2.then(undefined, undefined)
//执行完p2,p2变为fulfilled后p1才变为fullfilled
.then((res) => {
console.log(res)
})
Promise.resolve().then(() => {
console.log(1);
}).then(() => {
console.log(2);
}).then(() => {
console.log(3);
}).then(() => {
console.log(5);
}).then(() =>{
console.log(6);
})
axios(option)
.then(res => {
if (res.status === 200) {
resolve(res.data); //响应状态码为200,resolve
console.log(res.data);
} else {
reject(res.data); //不是200,在200~300之间,reject抛出
}
})
.catch(err => {
Message({
type: "error",
message: err.response.data.msg
});
reject(err);//
});
//当promiseA由pendding向settled过渡后,两个then会被调用。注意,这里并非链式调用。
const promiseA = new Promise(myExecutorFunc);
const promiseB = promiseA.then(handleFulfilled1, handleRejected1);
const promiseC = promiseA.then(handleFulfilled2, handleRejected2);
await promise
返回的就是其结果。但是如果 promise 被 reject,它将 throw 这个 error,此时async函数中最好有一个trycatch包裹住await语句。 .catch
处理 reject()
中抛出的try{}catch{}
try{}catch{}
本身是同步代码,无法捕获异步错误 async/await
配合try{}catch{}
try{await...}catch(error){...}
.catch(error){...}
unhandledrejection
事件处理程序(用于浏览器,以及其他环境的模拟),以跟踪未处理的 error
window.addEventListener('unhandledrejection', function(event) {
// 这个事件对象有两个特殊的属性:
alert(event.promise); // [object Promise] - 生成该全局 error 的 promise
alert(event.reason); // Error: Whoops! - 未处理的 error 对象
});
new Promise(function() {
throw new Error("Whoops!");
}); // 没有用来处理 error 的 catch
thenable对象:
确切地说,处理程序(handler)返回的不完全是一个 promise,而是返回的被称为 “thenable” 对象 — 一个具有方法 .then 的任意对象。它会被当做一个 promise 来对待。
JavaScript 检查在由 .then 处理程序(handler)返回的对象:如果它具有名为 then 的可调用方法,那么它将调用该方法并提供原生的函数 resolve 和 reject 作为参数,并等待直到其中一个函数被调用。
这个特性允许我们将自定义的对象与 promise 链集成在一起,而不必继承自 Promise。