重学 MDN Web API 文档: Promise All In One
Promise
const myPromise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("foo");
}, 300);
});
// 错误用法 ❌
myPromise.then((res, err) => {
console.log(`res =`, res);
console.log(`err =`, err);
});
// res = foo
// err = undefined
// Promise {<fulfilled>: undefined}
const myPromise2 = new Promise((resolve, reject) => {
setTimeout(() => {
reject("bug");
}, 0);
});
// 错误用法 ❌
myPromise2.then((res, err) => {
console.log(`res =`, res);
console.log(`err =`, err);
});
// ❌ Promise {<rejected>: 'bug'}
// Uncaught (in promise) bug
myPromise2.then((res) => {
console.log(`res =`, res);
}, (err) => {
console.log(`err =`, err);
});
// err = bug
// Promise {<fulfilled>: undefined}