We summarize the asynchronous writing method through a case, which simulates asynchrony through setTimeout. The function is to return what is input, and the goal is to achieve three consecutive interdependent serial asynchronous calls and concatenate the results.

Notation 1: callback function

Advantages:

  1. Simple, the easiest way to write it;

Disadvantages:

  1. Bad code to read and maintain, easy to write callback hell
  2. Only one callback function can be specified per task;
  3. Do not use a try catch to catch an error. Do not return directly.
function asyncCallback(content, callback) {
  setTimeout(callback, 200, content);
}

asyncCallback('1111'.(content) = > {
  console.log(content);
  asyncCallback(`${content}2222 `.(content) = > {
    console.log(content);
    asyncCallback(`${content}3333 `.(content) = > {
      console.log(content);
    });
  });
});
Copy the code

Notation 2: Event listening

Advantages:

  1. Multiple events can be bound, and each event can specify multiple callback functions;
  2. It solves the callback hell and can achieve decoupling, which is conducive to modularity.

Disadvantages:

  1. The entire application becomes event-driven, and the flow becomes unclear
  2. Poor readability, it is difficult to sort out the main process of the program.
const EventEmitter = require('events');
const eventEmitter = new EventEmitter();

function asyncEvent(content, eventType) {
  setTimeout(() = > {
    eventEmitter.emit(eventType, content);
  }, 200);
}

let globalContent = ' ';
asyncEvent('1111'.'event1');
eventEmitter.on('event1'.(content) = > {
  globalContent = `${globalContent}${content}`;
  console.log(globalContent);
  asyncEvent('2222'.'event2');
});
eventEmitter.on('event2'.(content) = > {
  globalContent = `${globalContent}${content}`;
  console.log(globalContent);
  asyncEvent('3333'.'event3');
});
eventEmitter.on('event3'.(content) = > {
  globalContent = `${globalContent}${content}`;
  console.log(globalContent);
});
Copy the code

Method 3: promise

Advantages:

  1. The callback hell is solved, and the code is relatively clean and intuitive
  2. The ability to catch errors through callback functions

Disadvantages:

  1. There is no way to cancel a Promise, which will be executed once it is created and cannot be cancelled halfway through
  2. If the callback function is not set, errors thrown inside a Promise are not reflected outside
  3. When in the Pending state, there is no way to know the current progress (just started or about to complete).
function asyncPromise(content) {
  return new Promise((resolve) = > {
    setTimeout(() = > {
      resolve(content);
    }, 200);
  });
};

asyncPromise('1111').then((data) = > {
  console.log(data);
  return asyncPromise(`${data}2222 `);
}).then((data) = > {
  console.log(data);
  return asyncPromise(`${data}3333 `);
}).then((data) = > {
  console.log(data);
  return asyncPromise(`${data}3333 `);
}).catch((err) = > {
  console.log(err);
})
Copy the code

Method 4: async/await

Advantages:

  1. The code is simple and intuitive, elegantly solving the callback hell problem;
  2. More broadly, await commands can be followed by Promise objects and primitive types;
  3. More semantic, making asynchronous code read like synchronous code

Disadvantages:

  1. Multiple asynchronous code without dependencies using await results in performance degradation.
async function asyncPromise(content) {
  return new Promise((resolve) = > {
    setTimeout(() = > {
      resolve(content);
    }, 200);
  });
};
async function getContent() {
  const content1 = await asyncPromise('1111');
  const content2 = await asyncPromise('2222');
  const content3 = await asyncPromise('3333');
  console.log(`${content1}${content2}${content3}`);
}
getContent();
Copy the code

Reference: zhuanlan.zhihu.com/p/57548254