八、Promise相关面试题汇总

郁子大约 2 分钟约 487 字笔记渡一教育笔面试题甄选谢杰

(一)下面代码的输出结果是什么

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

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

console.log(4);
1 【先new再赋值给promise】
2
4
3

(二)下面代码的输出结果是什么

const promise = new Promise((resolve, reject) => {
  console.log(1);
  setTimeout(() => {
    console.log(2);
    resolve();
    console.log(3);
  });
});

promise.then(() => {
  console.log(4);
});

console.log(5);
1
5
2
3
4

(三)下面代码的输出结果是什么

const promise1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve();
  }, 1000);
});
const promise2 = promise1.catch(() => {
  return 2;
});

console.log("promise1", promise1);
console.log("promise2", promise2);

setTimeout(() => {
  console.log("promise1", promise1);
  console.log("promise2", promise2);
}, 2000);
promise1, Promise { <pending> }
promise2, Promise { <pending> }
promise1, Promise { <fulfilled>: undefined }
promise2, Promise { <fulfilled>: undefined }

(四)下面代码的输出结果是什么

async function m() {
  const n = await 1;
  console.log(n);
}

m();
console.log(2);
2
1

(五)下面代码的输出结果是什么

async function m() {
  const n = await 1;
  console.log(n);
}

(async () => {
  await m();
  console.log(2);
})();

console.log(3);
3
1
2

(六)下面代码的输出结果是什么

async function m1() {
  return 1;
}

async function m2() {
  const n = await m1();
  console.log(n);
  return 2;
}

async function m3() {
  const n = m2();
  console.log(n);
  return 3;
}

m3().then((n) => {
  console.log(n);
});

m3();

console.log(4);
Promise { <pending> }  【带then的m3的n】
Promise { <pending> }  【m3的n】
4
1 【带then的m3完成,m2的n】
3 【带then的m3的then】
1 【m3完成,m2的n】

(七)下面代码的输出结果是什么

Promise.resolve(1).then(2).then(Promise.resolve(3)).then(console.log);
1

(八)下面代码的输出结果是什么

var a;
var b = new Promise((resolve, reject) => {
  console.log("promise1");
  setTimeout(() => {
    resolve();
  }, 1000);
})
  .then(() => {
    console.log("promise2");
  })
  .then(() => {
    console.log("promise3");
  })
  .then(() => {
    console.log("promise4");
  });

a = new Promise(async (resolve, reject) => {
  console.log(a);
  await b;
  console.log(a);
  console.log("after1");
  await a;
  resolve(true);
  console.log("after2");
});

console.log("end");
promise1
undefined 【a,未赋值】
end
promise2
promise3
promise4
Promise { <pending> } 【a,全局代码已执行完成,已赋值】
after1

(九)下面代码的输出结果是什么

async function async1() {
  console.log("async1 start");
  await async2();
  console.log("async1 end");
}
async function async2() {
  console.log("async2");
}

console.log("script start");

setTimeout(function () {
  console.log("setTimeout");
}, 0);

async1();

new Promise(function (resolve) {
  console.log("promise1");
  resolve();
}).then(function () {
  console.log("promise2");
});
console.log("script end");
script start
async1 start
async2
promise1
script end
async1 end
promise2
setTimeout
上次编辑于: