ES6 interview questions--Promise related

1、

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

The output results are: 1, 2, 4, 3.

  Problem-solving idea: The then method is executed asynchronously.

2、

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('success')
    reject('error')
  }, 1000)
})
promise.then((res)=>{
  console.log(res)
},(err)=>{
  console.log(err)
})

Output result: success

  Problem-solving idea: Once the state of Promise changes, it cannot be changed.

3、

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

output: 1

  Problem-solving idea: The parameter expectation of the then method of Promise is a function, and if a non-function is passed in, value penetration will occur.

4、

setTimeout(()=>{
  console.log('setTimeout')
})
let p1 = new Promise((resolve)=>{
  console.log('Promise1')
  resolve('Promise2')
})
p1.then((res)=>{
  console.log(res)
})
console.log(1)

Output result:

    Promise1
    1
    Promise2
    setTimeout

  Problem-solving idea: This involves the execution queue problem of js. The entire script code is placed in the macrotask queue. When the setTimeout is executed, a new macrotask queue will be created. However, promise.then is placed in another task queue , microtask queue . The execution engine of the script will take a task in the macrotask queue and execute it. Then all the microtask queues are executed in sequence, and then the macrotask queue where setTimeout is located starts to execute in sequence. (Refer to https://www.zhihu.com/question/36972010 for details )

5、

Promise.resolve(1)
    .then((res) => {
        console.log(res);
        return 2;
    })
    .catch((err) => {
        return 3;
    })
    .then((res) => {
        console.log(res);
    });

Output: 1 2

  Problem-solving idea: Promise first resolves(1), and then executes the then function, so it outputs 1, and then returns 2 in the function. Because it is a resolve function, the subsequent catch function will not be executed, but the second then function will be executed directly, so 2 will be output.

6、

const promise = new Promise((resolve, reject) => {
setTimeout(() => {
console.log( ' start ' );
resolve('success');
}, 5000);
});
 
const start = Date.now();
promise.then((res) => {
console.log(res, Date.now() - start);
});
 
promise.then((res) => {
console.log(res, Date.now() - start);
});

Output result:

    Start

    success 5002

    success 5002

  Problem-solving idea: Promise's .thenor .catchcan be called multiple times, but here the Promise constructor is only executed once. In other words, once the internal state of promise changes and has a value, then each subsequent call .then or .catchwill directly get the value.

7、

let p1 = new Promise((resolve,reject)=>{
  let num = 6
  if(num<5){
    console.log('resolve1')
    solve(num)
  }else{
    console.log('reject1')
    reject (num)
  }
})
p1.then((res)=>{
  console.log('resolve2')
  console.log(res)
}, (reg) => {
  console.log('reject2')
  let p2 = new Promise((resolve,reject)=>{
    if(rej*2>10){
      console.log('resolve3')
      resolve(rej*2)
    }else{
      console.log('reject3')
      reject (rej * 2 )
    }
  })
  return p2
}).then((res)=>{
  console.log('resolve4')
  console.log(res)
}, (reg) => {
  console.log('reject4')
  console.log(rej)
})

Output result:

    reject1
    reject2
    resolve3
    resolve4
    12

  Problem-solving ideas: We said above that the advanced point of Promise is that you can continue to write Promise objects and return them in the then method.

8. Implement a simple promise

function Promise(fn){
  var status = 'pending'
  function successNotify(){
      status = ' fulfilled ' // status becomes fulfilled 
      toDoThen.apply(undefined, arguments) // execute callback 
  }
  function failNotify(){
      status = ' rejected ' // status becomes rejected 
      toDoThen.apply(undefined, arguments) // execute callback 
  }
  function toDoThen(){
      setTimeout(() =>{ // ensure that the callback is executed asynchronously 
          if (status === ' fulfilled ' ){
               for (let i = 0 ; i< successArray.length;i ++ ) {
                  successArray[i].apply(undefined, arguments) // Execute the callback function in then 
              }
          }else if(status === 'rejected'){
              for(let i =0; i< failArray.length;i ++)    {
                  failArray[i].apply(undefined, arguments) // Execute the callback function in then 
              }
          }
      })
  }
  var successArray = []
   var failArray = []
  fn.call(undefined, successNotify, failNotify)
  return {
      then: function(successFn, failFn){
          successArray.push(successFn)
          failArray.push(failFn)
          return undefined // A Promise should be returned here 
      }
  }
}

Problem-solving ideas: resolve and reject in Promise are used to change the state of Promise and pass parameters, and the parameters in then must be functions that are executed as callbacks. Therefore, when the Promise changes the state, the callback function is called, and the callback function to be executed is selected according to the different state.

 

Reprinted from: https://www.cnblogs.com/lunlunshiwo/archive/2018/04/16/8852984.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324478720&siteId=291194637