Promise 题目

题目 1

async function async1 () {
  console.log('async1 start');
  setTimeout(() => {
    console.log('timer1 start');
  }, 500);
  Promise.resolve().then((res) => {
    console.log('promise1');
  })
  await async2();
  setTimeout(() => {
    console.log('timer1 end');
  }, 500);
  console.log('async1 end');
}
 
async function async2 () {
  setTimeout(() => {
    console.log('timer2');
  }, 1000);
  Promise.resolve().then((res) => {
    console.log('promise2');
  })
  console.log('async2');
}
 
async1();
 
console.log('start');
解答 async1 start async2 start promise1 promise2 async1 end timer1 start timer1 end timer2

题目2

const promise = () =>
  new Promise((resolve, reject) => {
    console.log(1)
    new Promise((resolve, reject) => {
      console.log(2)
      setTimeout(() => {
        resolve(3)
        console.log(4)
      })
    }).then((data) => {
      setTimeout(() => {
        console.log(5)
      })
      console.log(data)
    })
    setTimeout(() => {
      resolve(6)
      console.log(7)
    })
  }).then((data) => {
    console.log(data)
    setTimeout(() => {
      console.log(8)
    })
    console.log(9)
  })
 
promise()
解答 1 2 4 3 7 6 9 5 8

题目 2

const promise = () => {
  Promise.resolve()
    .then(() => {
      console.log(1)
      return Promise.resolve(4)
    })
    .then((res) => {
      console.log(res)
    })
 
  Promise.resolve()
    .then(() => {
      console.log(2)
    })
    .then(() => {
      console.log(3)
    })
    .then(() => {
      console.log(5)
    })
    .then(() => {
      console.log(6)
    })
}
 
promise()
解答 1 2 3 5 4 6 我最开始的答案是 124356,看了promise 手写以后发现,在 then 中 return 一个 Promise 的时候,会创建一个 then,但是不执行。所以会导致在两个队列之后才执行。如果把第一个改成 return 4 就会是我开始的答案

实现一个请求池