1、promise.then()传入的不是函数,会发生值穿透
Promise.resolve(1)
.then(2)
.then(Promise.resolve(3))
.then(console.log)
//1
Promise.resolve(1)
.then(function(){return 2})
.then(Promise.resolve(3)) //没有return相当于独立的promise,后续then不会接受到
.then(console.log)
//2
Promise.resolve(1)
.then(function(){return 2})
.then(function(){return Promise.resolve(3)})
.then(console.log)
//3
2、promise.then()中不能return promise自身,否则会造成死循环
const promise = Promise.resolve()
.then(() => {
return promise
})
promise.catch(console.error)
/*TypeError: Chaining cycle detected for promise #<Promise>
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
at Function.Module.runMain (module.js:667:11)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:607:3
*/
3、Promise,then()中return 一个错误,不会被后续的catch接住,throw一个错误或promise.reject()会被catch住
Promise.resolve()
.then(() => {
return new Error('error!!!')
})
.then((res) => {
console.log('then: ', res)
})
.catch((err) => {
console.log('catch: ', err)
})
/*then: Error: error!!!
at Promise.resolve.then (...)
at ...
*/
Promise.resolve()
.then(function success (res) {
throw new Error('error')
}, function fail1 (e) {
console.error('fail1: ', e)
})
.catch(function fail2 (e) {
console.error('fail2: ', e)
})
/*fail2: Error: error
at success (...)
at ...
*/
4、字节面试题
setTimeout(() => {
console.log(1);
})
const p1 = Promise.resolve(() => {
console.log(2);
})
const p2 = new Promise((resolve, reject) => {
console.log(3);
resolve();
})
Promise.race([p1, p2]).then(() => {
console.log(4);
})
Promise.all([p1, p2]).then(() => {
console.log(5);
})
console.log(6);
//3 6 4 5 1
async function async1() {
console.log('async1 start');
await async2();
console.log('async1 end');
}
async function async2() {
console.log('async2 start');
return new Promise((resolve, reject) => {
resolve();
console.log('async2 promise');
})
}
console.log('script start');
setTimeout(function() {
console.log('setTimeout');
}, 0);
async1();
new Promise(function(resolve) {
console.log('promise1');
resolve();
}).then(function() {
console.log('promise2');
}).then(function() {
console.log('promise3');
});
console.log('script end');
/*script start
async1 start
async2 start
async2 promise
promise1
script end
promise2
promise3
async1 end
setTimeout
*/