This is the third day of my participation in Gwen Challenge

Promise is a landmark feature update in the evolution of asynchronous JavaScript programming that was first proposed and implemented by the community until the release of ES6, which standardized its use and provided Promise objects natively

  • throughthenFunction chain call mode, in the form of a preliminary solutionThe callback hellThe problem of
  • Become a subsequentasync/await,fetchAnd so on

Promise features

  • Asynchronous tasks
  • Value through
  • resolve/rejectNo interruption of execution
  • catchthen rejectHandleThe difference between

Asynchronous tasks

  • new PromiseIt is executed synchronously
  • Promisethen catch finallyIs executed asynchronously
1 -> 3 -> 2 -> 4
console.log(1)
new Promise((resolve) = > {
    console.log(3)
    resolve(4)
})
.then((data) = > {
    console.log(data)
})
console.log(2)
Copy the code

Value through

The Promise’s then catch parameter is expected to be a function, and value penetration occurs when passing a non-function

Promise.resolve(1)
  .then(2)
  .then(Promise.resolve(3))
  .then(console.log) / / 1
Copy the code

Resolve /reject Does not interrupt execution

Resolve/Reject simply changes the state of the Promise object and does not interrupt the current execution. We sometimes subconsciously think that resolve/ Reject directly moves the program to the next phase, but it does not

// The following code output order: 1 -> 3 -> 2
new Promise((resolve) = > {
    console.log(1)
    resolve(2)
    console.log(3)
})
.then((data) = > {
    console.log(data)
})
Copy the code

Catch and then rejectHandle

  • catchCan capturePromise resolveBefore thethrow Errorerror
  • then rejectHandlerUnable to capture siblingsthen resolveHandlerErrors in the
new Promise((resolve) = > {
    resolve(1)
    throw new Error('err') // Will not enter a Promise catch
})

new Promise((resolve) = > {
    resolve()
})
.then(() = > {
    throw new Error('err')},() = > {
    Failed to catch error err in then rejectHandler of the same class
})
Copy the code

Promise static method feature

Promise.all

The promise.all argument takes an iterable (usually an array) and returns a new Promise object. MDN: promise.all ()

  • If the argument is an empty array, enterthen
  • If the parameter array does not containPromiseObject into then, for examplePromise. All ([1, 2, 3])
  • If an elementPromise reject, will enter immediatelyPromise.allcatch, but does not affect the continuation of the Promise of other elements
  • If you want to know which one failed, you can find it in the elementPromiserejectIdentified in

If the array element Promise handles its own internal error and returns a resolve Promise, it will not result in a promise.all catch

Promise.race

The promise.race parameter is the same as promise.all. Refer specifically to MDN: promise.race ().

  • If the argument is an empty array,then catchDon’t perform
  • If the array is not empty, based on the first element returnedPromiseresolve rejectImmediately corresponding to entryPromise.racethen catch
  • No matter the first elementPromiseWhat is the result of, without affecting other elementsPromiseContinue to perform

Promise.allSettled

Promise. AllSettled introduces standard Promise from ES11. AllSettled waits for all element promises to complete (resolve or reject) and then

When can I enter promises.allsettled catch? At some Promise throw Error!

And promise.allsettled catch catches every error in a Promise, so it is possible to execute multiple times (Promise.all will only catch the first error).

const promise1 = new Promise(function(resolve, reject) {
  setTimeout(() = > {
    throw Error(1)},100)});const promise2 = new Promise(function(resolve, reject) {
  setTimeout(() = > {
    throw Error(2)},200)});Promise.allSettled([promise1, promise2])
  .then((value) = > {
    console.log('then', value)
  })
  .catch((err) = > {
    // a promise1 error is captured after 100ms and a promise2 error is captured after 200ms
    console.log('catch', err)
  })
Copy the code

Promise.any

Promise.any is introduced by ES12

  • If the elementPromiseThere is aresolve, I entered aPromise.anythen
  • If the elementPromiseAll of themreject, I entered aPromise.anycatch

Promise/A + specification

As mentioned above, Promises are standard native objects provided by ES6. When our code needs to be compiled into ES5 or below, we need to introduce Polyfill. The Promise in Polyfill is written according to the Promise/A+ specification

See the Promise/A+ specification for details

  • aPromiseMust be in one of the following three states: Wait state (Pending), execution state (Fulfilled) and rejection states (Rejected)
    • In the wait state,promiseYou can migrate to the execute or reject state
    • In the execution state,promiseYou cannot migrate to any other state and must have an immutable end value
    • In the rejection state,promiseYou cannot migrate to any other state and must have an immutable data cause
  • The THEN method must be implemented
    • thenThe function takes two arguments
    • thenFunction argument if it is not a function, the argument is ignored
    • thenThe function can be separated by apromiseMultiple calls
    • Must return onepromiseThe instance

Write in the last

All and promise.race, one Promise reject interrupts the other promises. I look up the documents and write demo tests, all of which prove that neither interrupts nor waits. Hope to give a demo in the comments section