Problem description

In order to solve the problem of the callback hell caused by multi-layer nesting of front-end asynchronous functions, and the problem of the callback hell error is not easy to catch. So, the rule makers have added a new feature in ES6 called Promise. This article mainly records the application scenarios of promise. all and promise.race and illustrates them with examples.

I won’t go over the basic concept of Promise here.

Promise. All methods

In a nutshell: promise.all ().then() works when multiple asynchronous tasks are processed and all of them get results.

For example, when the user clicks the button, a pop-up dialog box will pop up, in which two parts of data are displayed. The two parts of data are respectively obtained by different back-end interfaces.

In the initial case after the popup, let the popup be in the state of data loading. When the two parts of data are obtained from the interface, let the state of data loading disappear. Let the user see these two parts of the data.

In this case, we need both asynchronous interfaces to request processing when both tasks are completed, so we can easily implement this using the promise.all method. Let’s look at the code

Code attached

<template>
  <div class="box">
    <el-button type="primary" plain @click="clickFn">Click on the pop-up box</el-button>
  </div>
</template>

<script>
export default {
  name: "App".methods: {
    clickFn() {
      this.alertMask = true; // Open the pop-up box
      this.loading = true; // There is no data yet, so the loading effect is displayed

      // The first asynchronous task
      function asyncOne() {
        let async1 = new Promise(async (resolve, reject) => {
          setTimeout(() = > {
            // Here we use timer to simulate the return result of the request from the back end, after all, it is asynchronous
            let apiData1 = "The first interface returns data.";
            resolve(apiData1);
          }, 800);
        });
        return async1;
      }
      console.log("Asynchronous Task 1", asyncOne());  // Returns a Promise object

      // The second asynchronous task
      function asyncTwo() {
        let async2 = new Promise(async (resolve, reject) => {
          setTimeout(() = > {
            let apiData2 = "The second interface returns data.";
            resolve(apiData2);
          }, 700);
        });
        return async2;
      }
      console.log("Asynchronous Task 2", asyncTwo()); // Returns a Promise object

      let paramsArr = [asyncOne(), asyncTwo()]

      // Promise.all takes an array of parameters, each of which is a Promise object
      // We get the result of.all in the.then method. The result is an array, and each item in the array
      // This corresponds to the value returned by each item in the.all array
      Promise
      .all(paramsArr)
      .then((value) = > {
        console.log("Results of the promise.all method", value);
        this.loading = true; // Now we have data, so we turn off loading effects}); ,}}};</script>
Copy the code

Print the resulting graph

Promise. Race method

First place only

Promise.race isn’t really used much, if at all. We can make a demand like this:

For example: click the button to send a request, when the back-end interface exceeds a certain time, say more than three seconds, no result is returned, we will prompt the user to request timeout

Code attached

<template>
  <div class="box">
    <el-button type="primary" plain @click="clickFn">Click on the test</el-button>
  </div>
</template>

<script>
export default {
  name: "App".methods: {
    async clickFn() {

      // The first asynchronous task
      function asyncOne() {
        let async1 = new Promise(async (resolve, reject) => {
          setTimeout(() = > {
            // Here we use timer to simulate the return result of the request from the back end, after all, it is asynchronous
            let apiData1 = "Some request.";
            resolve(apiData1);
          }, 4000);
        });
        return async1;
      }
      console.log("Asynchronous Task 1", asyncOne());  // Returns a Promise object in a pending state

      // The second asynchronous task
      function asyncTwo() {
        let async2 = new Promise(async (resolve, reject) => {
          setTimeout(() = > {
            let apiData2 = "Timeout warning";
            resolve(apiData2);
          }, 3000);
        });
        return async2;
      }
      console.log("Asynchronous Task 2", asyncTwo()); // Returns a Promise object in a pending state

      // Promise.race receives an array of parameters, similar to promise.all. But the Race method yields only one result
      // The value of the fastest runner is used as the result
      let paramsArr = [asyncOne(), asyncTwo()]

      Promise
      .race(paramsArr)
      .then((value) = > {
        console.log("Results of the promise.race method", value);
        if (value == "Timeout warning") {
          this.$message({
            type:"warning".message:"Interface request timed out"})}else{
          console.log('Normal operation is ok'); }})},},};</script>
Copy the code

I won’t print it here, so it looks like the print above

conclusion

  • Promise. All takes care of the slowest runner, and ends when the slowest runner finishes.
  • Promise.race also receives an array, but instead gets the fastest runner in the array, which ends as soon as the fastest runner finishes.