Promise面试题

几道打印的基础题

题1

const promise = new Promise((resolve, reject) => {
console.log(1)
resolve("success")
console.log(2)
})

promise.then(() => {
console.log(3)
})

console.log(4)

1 2 4 3

题2

const promise1 = new Promise((resolve, reject) => {
console.log(1)
resolve("success")
})

const promise2 = promise1.then(() => {
console.log(2)
})

console.log(3, promise1)
console.log(4, promise2)
image.png

题3

const fn = () => (new Promise((resolve, reject) => {
console.log(1)
resolve("success")
}))

fn().then((res) => {
console.log(res)
})

console.log(2)

1
2
success

题4

const fn = () => (new Promise((resolve, reject) => {
console.log(1)
resolve("success")
}))

console.log(2)

fn().then((res) => {
console.log(res)
})

2
1
success

Promise结合setTimeout

题1

console.log(1)
setTimeout(() => {
console.log(2)
})
Promise.resolve().then(() => {
console.log(3)
})
console.log(4)

1 4 3 2

题2

const promise = new Promise((resolve, reject) => {
console.log(1)
setTimeout(() => {
console.log(2)
resolve("success")
console.log(3)
}, 0)
console.log(4)
})
promise.then((res) => {
console.log(res)
})
console.log(5)

1 4 5 2 3 success

题3

Promise.resolve().then(() => {
console.log('1');
const timer1 = setTimeout(() => {
console.log('2');
}, 0);
})

const timer2 = setTimeout(() => {
console.log('3');
Promise.resolve().then(() => {
console.log('4');
})
}, 0);

console.log('5');

5 1 3 4 2

题4

const promise1 = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("success")
}, 1000)
})
const promise2 = promise1.then(() => {
throw new Error("error message")
})
console.log("promise1", promise1)
console.log("promise2", promise2)
setTimeout(() => {
console.log("promise1", promise1)
console.log("promise2", promise2)
}, 2000)
image.png