js implements two asynchronous requests, requiring the completion of the previous request, taking the result of the previous request, and requesting the next data.

Record a function that was developed and implemented in actual work today: there are two asynchronous requests, the previous request is required to be completed, the result of the previous request is obtained, and the next piece of data is requested.

The purpose is to record, if there are deficiencies, please advise. Without further ado, let's go!

The first idea: use async/await syntax to execute two asynchronous requests sequentially

For example:

async getData() {
    
    
  // 发送第一个请求,获取 id
  const res1 = await this.$http.get('/api/get-id');
  const id = res1.data.id;

  // 使用 id 发送第二个请求
  const res2 = await this.$http.get(`/api/get-data?id=${
      
      id}`);
  console.log(res2.data);
}

In this example, we first use the await keyword to wait for the response of the first request. Then, we get the id in the response data and use this id to send the second request. You can also use try/catch statements in functions that execute asynchronous code to catch/handle errors.

However, if the two requests are written in different functions, and the results of other functions are requested in this function, and then other operations are performed, it will often appear that the result of the first function has not been received, and the next request The phenomenon is completed.
For example the following code:

async getData1() {
    
    
  // 发送第一个请求,获取 id
  const res1 = await this.$http.get('/api/get-id');
  this.id = res1.data.id;
}
async getData2() {
    
    
	await this.getData1()
	console.log(this.id) //此时的id就有可能为undefined;
  // 使用 id 发送第二个请求
  const res2 = await this.$http.get(`/api/get-data?id=${
      
      this.id}`);
  console.log(res2.data);
}

So how to solve this situation? I thought of the second way of thinking.

The second idea: use Promise.then() to execute two asynchronous requests sequentially

The implementation code is as follows:

  getData1() {
    
    
    return new Promise((resolve, reject) => {
    
    
      // 发送第一个请求,获取 id
      this.$http.get('/api/get-id').then(({
     
      data }) => {
    
    
          this.id = data.id;
          resolve();
        }).catch(err => {
    
    
          console.log(err.msg);
          reject(err.msg);
        });
    })
  }
  getData2() {
    
    
    this.getData1().then(() => {
    
    
      console.log(this.id) //此时的id就会正常出来;
      // 使用 id 发送第二个请求
      this.$http.get(`/api/get-data?id=${
      
      this.id}`).then(({
     
      data }) => {
    
    
        console.log(data);
      }).catch(err2 => {
    
    
        console.log(err2.msg);
        reject(err2.msg);
      });
    }).catch(err => {
    
    
      console.log(err.msg);
      reject(err.msg);
    });
  }

This idea is mainly to use Promise to ensure the execution order of the getData1 function. First you need to modify the getData1 function to return a Promise object. When calling getData1, use the .then() method to perform subsequent operations. If an error occurs, the function in .catch() will be executed, and error handling can be performed in this function.

Thumbs up!
Finished! ! ! Sprinkle flowers! !

get off work!  !

Guess you like

Origin blog.csdn.net/lFFFFFFl/article/details/128569134