[interview] advanced application questions to test your familiarity with Promise

Posted by phpion on Wed, 15 Dec 2021 14:31:02 +0100

Author: Hannah Lin
Source: medium

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.
This article GitHub https://github.com/qq449245884/xiaozhi It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

This article should have been written two years ago, because it was an interview question for a well-known Udxxx online course. Now I can only recall it with my weak memory. The advanced problem is because I thought I knew Promise, but I was KO when I met this application problem.

People who have touched Promise may find it easy to deal with asynchronous async.

var p = num => new Promise((resolve, reject) => {
    if(num <= 2) {
        setTimeout(resolve('Success!'), Math.random()*1000);
        return;
    }
    reject('Failure!') 
});

p(1)
  .then(res => { console.log(res)})
  .catch( error => { console.log(error)}); 
// "Success!"

However, in addition to the common fetch API, there are many advanced applications! Next, this question will test everyone's familiarity with Promise, because I really didn't know how to solve it at the beginning

Let's look at the topic

A total of 10 tasks can be call ed at most 3 at a time. Each task needs to be completed at a different time.

Please use the template provided below to write out the methods that can complete these 10 tasks.

/**
 * @return { promise }
 * Write a function to execute the task
 */
function task(){}
class handleTask{
  constructor(maxCount){
    this.maxCount = maxCount;
    this.pendingTask = [];
    this.completed = 0; 
  }
  run(tasks){}
}

Infer which variables may be required according to the topic and the provided function:

  • totalTask: number = 10 → how many tasks in total
  • maxTask: number = 3 → execute at most several tasks at a time
  • pendingTask: [number] = [promise, promise...] → wait for the task to be executed
  • completed:number → Track several Tasks successfully

It's easy to write a promise task,

/**
 * @return { promise }
 * Write a function to execute the task
 */
function task(){
  return new Promise((resolve, reject) => {
      console.log('running')
      setTimeout(resolve(), Math.random()*1000) // Each task takes different time, so random is used here
  }).then(() => {
      console.log('done')
  }).catch(() => {
      console.log('error')
  })
}

But when I want to write the method of run(), I'm completely stuck:

  • I don't know how to run the task three times at a time. Is it run three times?
  • How do you execute other task s until the execution is finished?

count

I always think so, but I don't know how to solve it. In fact, I need a very important thing count to calculate which task you are executing now

Count → calculate the Tasks being executed. If count < 3, task() will be executed, so three Tasks will be executed first.

When one of the tasks is completed, count will be - 1, and then continue to do the next task

run(tasks){
      if(this.count < this.maxCount){
        this.count ++;
        tasks().then(() => {
          this.count --;
        })
      } 
}

pendingTask

Another key point is that pendingTask is used to save tasks to be processed, so it will be [4,5,6,7,8,9,10] at the beginning. When [1,2,3] one of the tasks is processed first, task 4 will be grabbed to continue processing, and pendingTask will also change to [5,6,7,8,9,10], as shown in the following figure:

run(tasks){
      if(this.count < this.maxCount){
        this.count ++;
        tasks().then(() => {
          this.count --;
          this.pendingTask.shift()
        })
      } else{
          this.pendingTask.push(tasks);
      }
}
class handleTask{
  constructor(maxCount){
    this.maxCount = maxCount; // 3
    this.count = 0;  
    this.pendingTask = [];
    this.completed = 0;
  }

  run(tasks){
    if(this.count < this.maxCount){
        this.count ++;
        tasks().then(() => {
          this.count --;
          this.completed ++;
          this.pendingTask.shift(0);
          
          console.log('completed: ', this.completed)
        })
      } else{
        this.pendingTask.push(tasks);
      }
  }
}

function task () {
  //...  slightly
}

let myTask = new handleTask(3);

for(let i=0; i< 10; i++){
  myTask.run(task);
}

Problem: only 3 tasks have been completed in total

But, it is found that completed is equal to 3 in the end, which means that only 3 tasks have been successfully completed! There must be something wrong.

Settle

This is because mytask run(task); It will run ten times in an instant (whether the task is completed or not), and the pendingTask will be [4,5,6,7,8,9,10] at first, and then because

if(this.count < this.maxCount){
    this.count ++;
    //  The first three task s will be completed one after another      
    tasks().then(() => {
        this.count --;
        this.pendingTask.shift(0);
    })
}

Only [1, 2, 3] will actually run into the if, while the pendingTask will be [7, 8, 9, 10], but in fact [4, 5, 6] will not be executed run:

In order to continue with the rest of the task, you should put this pendingTask. shift(0); , Change to

if(this.pendingTask.length > 0) this.run(this.pendingTask.shift())

This is a good time to test JS basic skills, if this Pendingtask is [4,5,6,7,8,9,10], that's this pendingTask. Shift() will return, 4; this.pendingTask becomes [5,6,7,8,9,10], that is, continue to leave task 4 in the run, so as to complete all tasks.

The bugs that may exist after code deployment cannot be known in real time. Afterwards, in order to solve these bugs, we spent a lot of time on log debugging. By the way, we recommend a useful BUG monitoring tool Fundebug.

Original text:
https://medium.com/starbugs/%...

communication

There are dreams and dry goods. Wechat search [Daqian world] pays attention to this bowl washing wisdom who is still washing dishes in the early morning.

This article GitHub https://github.com/qq44924588... It has been included. There are complete test sites, materials and my series of articles for the interview of front-line large factories.

Topics: Front-end