Skip to content

常见代码输出题

1. 考察promise输出结果

js
// 1
let p = new Promise((resolve,reject)=>{
    reject();
    resolve();
});
p.then(()=>console.log('成功'),()=>console.log('失败'));
js
const promise = new Promise((resolve,reject)=>{
    console.log(1);
    resolve();
    console.log(2);
})
promise.then(()=>{
    console.log(3);
})
js
Promise.resolve(1)
.then(res=>2)
.catch(err=>3)
.then(res=>console.log(res));
js
Promise.resolve(1)
.then(x=>x+1)
.then(x=>{throw new Error('My Error')})
.catch(()=>1)
.then(x=>x+1)
.then(x=>console.log(x))
.catch(console.error)

2. 考察宏任务和微任务:

颜色如何改变

js
document.body.style.background = "red";

Promise.resolve().then(res => {
  document.body.style.background = "yellow";
});
js
document.body.style.background = "red";

setTimeout(() => {
  document.body.style.background = "yellow";
});