This is the 27th day of my participation in the August More Text Challenge

Two, Promise to advance

2.1 Promise interdependence

const setDelay = (millisecond) = > {
  return new Promise((resolve, reject) = > {
    if (typeofmillisecond ! ='number') {
      reject(new Error('Parameter must be of type NUMbe'));
    }
    
    setTimeout(() = > {
      resolve('I'm late${millisecond}The output 'after milliseconds);
    }, millisecond);
  });
}
Copy the code
const setDelaySecond = (seconds) = > {
  return new Promise((resolve, reject) = >{
    if (typeofseconds ! ='number' || seconds > 10) {
      reject(new Error('Argument must be of type number and equal to 10'));
    }

    setTimeout(() = > {
      console.log(The setDelaySeconds function output is delayed${seconds}Seconds, total delay${seconds+2}Second `);
      
      resolve(setDelay(2000)) // This relies on a Promise
    }, seconds * 1000);
  });
}
Copy the code
setDelaySecond(3).then((result) = >{
  console.log(result);
  // "setDelaySeconds output is delayed by 2 seconds. Total delay is 5 seconds."
  // "I output after 2000 ms delay"
}).catch((err) = >{
  console.log(err);
})
Copy the code

This is done sequentially, but if you don’t want the coupling to be so high, you can execute setDelay first and then setDelaySecond.

2.2 Chain writing of Promise

Let’s rewrite setDelaySecond to reject dependencies and reduce coupling:

const setDelaySecond = (seconds) = > {
  return new Promise((resolve, reject) = >{
    if (typeofseconds ! ='number' || seconds > 10) {
      reject(new Error('Argument must be of type number and equal to 10'));
    }
    
    setTimeout(() = > {
      resolve('I'm late${seconds}The output after seconds is the second function ');
    }, seconds * 1000); })}Copy the code

If setDelaySecond returns the next Promise in the result of the first “then”, then we can continue the sequence:

setDelay(2000)
.then((result) = >{
  console.log(result)
  console.log('I got to step one.');
  return setDelaySecond(3)
})
.then((result) = >{
  console.log('I got to step two.');
  console.log(result);
}).catch((err) = >{
  console.log(err);
})
// I output after 2000 ms delay
// I got to the first step
// I got to step 2
// I output the second function after a delay of 3 seconds
Copy the code

The essence of the Promise chain is to pass a new Promise all the way down, meaning that then receives the Promise in the next step.

2.3 Promise error handling

Then has two callback arguments:

  • The first callback is the resolve callback, where the first parameter is used the most and the resolve value of the Promise of the previous step is returned.
  • The second callback is a reject callback. It is not used much, and usually is a reject callback. What is the difference between this and the catch callback?
setDelay(2000)
.then((result) = >{
  console.log(result)
  console.log('I got to step one.');
  return setDelaySecond(20)
})
.then((result) = >{
  console.log('I got to step two.');
  console.log(result);
}, (_err) = > {
  console.log('I made an error, I go in here and catch an error, but I don't go through a catch.');
})
.then((result) = >{
  console.log('I still continue to execute !!!! ')
})
.catch((err) = >{
  console.log(err);
})
Copy the code

As you can see, the output goes into the second parameter of then, reject, and no longer through catch.

setDelay(2000)
.then((result) = >{
  console.log(result)
  console.log('I got to step one.');
  return setDelaySecond(20)
})
.catch((err) = >{ // Move it up
  console.log(err); // Catch the last error that returns a Promise
})
.then((result) = >{
  console.log('I got to step two.');
  console.log(result);
}, (_err) = > {
  console.log('I made a mistake, but since catch is ahead of me, the mistake has already been caught. I don't have any more mistakes.');
})
.then((result) = >{
  console.log('I still continue to execute !!!! ')})Copy the code

You can see that after the catch, there are no errors.

Note:

  • The catch notation is for catching errors in the entire chain notation, while the then second argument is for the previous one that returned a Promise.
  • The precedence of the two methods is to see who is in front of the chain method. The first one catches the error first, and then there are no errors to catch. The precedence of the chain method is higher, and neither of the two methods is break, so the subsequent operation can be carried out without being affected.

Now that I have a lot of promises, do I need to write a lot of catches?

Don’t need to! You just need to catch at the end, because the chain-writing error handling is “bubbling”, any link in the chain will be caught, and the code after a link will not be executed.

setDelay('2000')
.then((result) = >{
  console.log("Step one is done.");
  console.log(result)
  return setDelaySecond(3)
})
.catch((err) = >{ 
  // the first chain is not executed, and the next chain is executed
  console.log(err);
})
.then((result) = >{
  console.log("Step two is complete.");
  console.log(result);
})
Copy the code

The catch in the chain is not the end point. After the catch, if there is a “then”, the execution will continue.

2.3 Promise stops jumping out