What is callback hell?

Asynchronous requests tend to be callback hell

How to optimize callback hell

  • Disassemble function: Disassemble each step into a single function

  • Event publish/listen mode

    • On the one hand, you can listen for an event and call back when it happens, and on the other hand, you can decouple your bundled code by issuing event-firing functions when something is done
  • Promise

    readFile('./sample.txt').then(content => {
         let keyword = content.substring(0, 5);
         return queryDB(keyword);
     }).then(res => {
         return getData(res.length);
     }).then(data => {
         console.log(data);
     }).catch(err => {
         console.warn(err);
     });
    Copy the code
  • generator

    • Generator is a new syntax in ES6. Add * after the function keyword to make the function a generator.
    const generator = function* () {
        yield 11;
        yield 22;
        return 33;
    }
    Copy the code
    • Executing generator returns an iterator object for traversing the state inside the generator
        let g = generator();
        g.next(); // { value: 11, done: false }
        g.next(); // { value: 22, done: false }
        g.next(); // { value: 33, done: true }
        g.next(); // { value: undefined, done: true 
    Copy the code
  • async/await

    • Any function can be an async function
    async function foo () {}; const foo = async function () {}; const foo = async () => {}; We can use await statements in async functions. Await is usually followed by a Promise object. Async function foo () {console.log(' start '); let res = await post(data); Console. log(' post completed, result: ${res} '); };Copy the code
    • When the above function executes to await, it simply means that the function suspends, waits for a Promise to return from await, and then executes the following statement