记一个Promise问题

我们来观察以下四段代码的区别:

// 1 setTimeout throw
const p1 = new Promise(function (resolve, reject) {
setTimeout(function () { throw new Error('test') }, 0)
});
p1.catch(function (error) { console.log('Catch1: ', error) });
// Uncaught Error: test


// 2 setTimeout reject
const p2 = new Promise(function (resolve, reject) {
setTimeout(function () { reject(new Error('test')) }, 0)
});
p2.catch(function (error) { console.log('Catch2: ', error) });
// Catch2: Error: test

// 3 throw
const p3 = new Promise(function (resolve, reject) {
throw new Error('test');
});
p3.catch(function (error) { console.log('Catch3: ', error) });
// Catch3: Error: test

// 4 reject
const p4 = new Promise(function (resolve, reject) {
reject(new Error('test'));
});
p4.catch(function (error) { console.log('Catch4: ', error) });
// Catch4: Error: test

thencatch返回新的Promise对象,finally返回本身。

allthencatch的调用优先级低于all的元素本身的thencatch

以下两者代码的区别:(定义Promise的时候会执行其中的代码)

const f = () => console.log('now');
Promise.resolve().then(f);
console.log('next');
// next
// now

const f = () => console.log('now');
(
() => new Promise(
resolve => resolve(f())
)
)();
console.log('next');
// now
// next