Is to see the code that yu Xi writes, feel this idea is very clever, use es6 oneself record by memory. The description of the problem is not accurate, please refer to me for details

Problem description

Function getValueFromRemote(index: number, cb: (value: Number => void) is an asynchronous function. You need to pass 31 parameters from 0 to 30 into the function and print the results in sequence.

The recursive method

The easiest way to think about it is the recursive method, which is a serial call, first calling 0, then returning 0 and then calling 1 in the callback function, as follows:

const count = 30;
function _getValue(i: number) {
  getValueFromRemote(i, (value) => {
    printResult(value);
    if (i <= count) {
      _getValue(i + 1); }}); }function printResult(value: number) {
  console.log("The value is " + value);
}

_getValue(0)
Copy the code

The advantage is that the logic is simple and easy to understand, the disadvantage is that the serial efficiency is too low

Array method

An array is used to store the returned result as follows:

const apiValue = [];
function _getValue(i: number) {
  getValueFromRemote(i, (value) => {
    apiValue[i] = {
      value,
      printed: false};if (i == 0 || apiValue[i - 1].printed) { printResult(i); }}); }function printResult(index: number) {
  console.log("The value is " + apiValue[index].value);
  apiValue[index].printed = true
  if (
    exist(apiValue[index + 1]) &&
    !apiValue[index + 1].printed
  ) {
    printResult(index + 1); }}function exist(thing: any) {
  returnthing ! = =undefined&& thing ! = =null;
}

for (let i = 0; i < 31; i++) {
  _getValue(i)
}
Copy the code

The above is the basic idea of the array method, that is, execute the function concurrently first, record the returned result in the corresponding order of the array first, and determine whether you need to be printed by judging whether the requests before and after are printed.

The idea is very clear and concise, which may be a very simple operation for algorithm masters, but WHEN I saw this algorithm for the first time, I still felt that MY ability is not enough.

Similarly, the question of how to ensure asynchronous sequential execution is often asked in interviews can be learned from this.