The problem background

There are three requests, and the return time of each request is unpredictable, depending on how the server processes it. We now require that the three requests be executed in order of precedence.

Solution model

Wrap all requests as promises for subsequent processing.

function factory(ajax) {
  return Promise.resolve(ajax);
}
Copy the code

Ajax requests need to be executed in a sequence that starts with the first one, completes the first one, and then executes the second one. Because promises can be called chained. Therefore, an execution chain should be constructed in a given order. In terms of formal structure

prev.then(curr).then(handler);
Copy the code

Curr execution must wait until the state of the PREV is determined. After the prev status is determined, the curr is executed, and the result of the curR is taken as a parameter to the handler.

function deal_by_order(ajaxs = []) {
  const resp = [];
  return ajaxs.reduce(function(prev, curr) {
    return prev.then(curr).then(function(data) {
      resp.push(data);
      return resp;
    });
  }, Promise.resolve());
}
Copy the code

Reduce is an important function in JS.

The test code

const time = (timer) = > {
  return new Promise((resolve) = > {
    setTimeout(() = > {
      resolve();
    }, timer);
  });
};
const ajax1 = () = >
  time(2000).then(() = > {
    console.log(1);
    return 1;
  });
const ajax2 = () = >
  time(1000).then(() = > {
    console.log(2);
    return 2;
  });
const ajax3 = () = >
  time(1000).then(() = > {
    console.log(3);
    return 3;
  });
Copy the code
deal_by_order([ajax1, ajax2, ajax3]).then((data) = > {
  console.log("done");
  console.log(data); // Data is [1, 2, 3]
});
Copy the code