Promise is a question that interviewers often ask

It’s also the basics. If you don’t know this, he may think you can’t get into the project quickly enough.

1 What is Promise

Promise is an asynchronous programming solution to the problem of callback hell. Callback hell is one asynchronous request nested within another asynchronous request, depending on its execution results. A Promise is an object from which you can get messages for asynchronous operations.

2 Features of Promises

The Promise object is a constructor that generates a Promise instance.

var promise = new Promise(executor){



}

Copy the code

Just as above, when you build a Promise object, you pass in an Executor function, where the main business process is executed.

When the Promise constructor executes, the executor function is called immediately, with resolve and reject passed as arguments. When resolve and reject are called, the Promise state is changed from pengding => depressing pending => Rejected, and once the state changes, it will not change again.

A call to resolve from the executor triggers a callback set by promise. then, and a call to reject triggers a callback set by promise. catch.

3 Synchronous or asynchronous

Promise is used to manage asynchronous programming and is itself synchronous. Ex. :

let p1 = new Promise((a)= > {

  setTimeout((a)= > {

    console.log(1)

  }, 1000)

  console.log(2)

})

console.log(3)

Copy the code

The sequence is 2, 3, and 1

let p1 = new Promise((resolve, reject) = > {

  console.log(1)

  resolve('know')

  console.log(2)

})

p1.then(result= > {

  console.log('success' + result)

}, reason => {

  console.log('failure' + result)

})

console.log(3)

Copy the code

(1, 2, 3) (1, 2, 3) (1, 2, 3) (1, 2, 3) (1, 2, 3) So output 3. 3 After the execution, clear the microtask queue. Print “Understanding success”

Ex. :

new Promise(resolve= > {

  resolve(a)

  / / an error

}).then(result= > {

  console.log(` success:${result}`)

  return result * 10

},reason => {

  console.log(` failure:${reason}`)

  If no exception is returned or a failed Promise instance is returned, the next "then" will continue

}).then(result= > {

  console.log(` success:${result}`)

}, reason => {

  console.log(` failure:${reason}`)

})

Copy the code

Output order: failed: referenceError A is not defined defined

4 then contains return

When a return value exists in the callback function for then:

.then((a)= > return 2)

.then(result= > console.log(result)) / / 2



.then((a)= > return new Promise())

.then(result= > console.log(result)) // New Promise above

Copy the code

So return is similar to resolve. When there is no return in the THEN, a new instance of the Promise is returned for the next THEN.

5. I Promise

5.1 Promise. Resolve ()

Promise.resolve(‘foo’) is equivalent to new Promise(resolve => resolve(‘foo’))

The promise.resolve parameter has one of four cases

1. The parameter is an instance of Promise

If the argument is a Promise instance, promise.resolve returns that instance intact.

const p1 = new Promise(function (resolve, reject){

  setTimeout((a)= > reject(new Error('fail')), 3000)

})



const p2 = new Promise((resolve, reject){

  setTimeout((a)= > resolve(p1), 1000)

})



p2.then(result= > console.log(result)).catch(err= > console.log(err))

Copy the code

P1 is reject after 3 seconds, p2 is P1 after 1 second, so p2. Then applies to the state change of P1. Finally, an ERR should trigger a catch

2. Arguments are not objects with THEN, or not objects at all

Promise.resolve('success').then(value= > {

  console.log(value) // success

}, function(value{



})

Copy the code

Arguments are passed to the then callback function

3. No parameters are required

The promise. resolve method, when called with no arguments, returns a Promise object with the resolve state

If you want a Promise object, you can call promise.resovle () directly

Promise.resolve().then((a)= > console.log('two'))

Copy the code

4. The parameter is the Thenable object

The Promise. Resolve method converts this object to a Promise object and immediately executes the THenable object’s THEN method.

let thenable = {

  thenfunction(resolve, reject{

    resolve()

  }

}

let P1 = Promise.resolve(thenable)



P1.then(function(value{console.log(value)})  / / 42

Copy the code

5.2 Promise. Reject

Return a Promise object with a reason for the rejection

new Promise((resolve, reject) = > reject(new Error('Wrong')))



/ / equivalent to the



Promise.reject(new Error('Wrong'))

Copy the code

5.3 Promise. All

Generates and returns a new Promise object that can use all the methods of the Promise instance.

The parameters are an array of Promise objects. This method returns only when all Promise objects become resolve.

let p1 = Promise.resolve(1)

let p2 = new Promise(resolve= > {

  setTimeout((a)= > {

    resolve(2)

  }, 1000)

})

let p3 = Promise.resolve(3)



Promise.all([p3, p2, p1]).then(result= > {

  console.log(result) // [3, 2, 1] returns in order

})

Copy the code

Note: If either Promise is reject, promise. all stops

Extension: When you invoke an interface in a project, you can have your own layer of promises

return new Promise((resolve, reject) = > {

  this.$service.network.get(url).then(res= > {

    resolve(res)

  })

})

Copy the code

5.4 Promise. AllSettled

It is similar to promise.all except that it will not short-circuit. Even if a Promise object reject, it does not affect the process. Finally, we can screen out successful Promise (filter).

5.5 Promise. Race

Promise.race, like all, takes an array of Promise objects as arguments

The difference between:

“All” is the then callback function when all objects become the FulFilled or Rejected state

Race is a callback to the then function only when the state of a Promise becomes a pity or Rejected.

5.6 Promise. Prototype. Finally

ES9 New Finally method returns the Promise, at the end of the Promise, whether the result is a pity or rejected. A callback function that executes.

This provides a way for the code that promises need to execute whether they succeed or not, eliminating the need to write once for then and once for catch.

this.loading = true

request().then(res= > {

  console.log(res)

})

.catch(err= > {

   console.log(err)

 })

.finally((a)= > {

   this.loading = false

})

Copy the code

Finally is executed only after the Promise state changes. The finally method’s callback takes no arguments and is independent of the state.

new Promise((a)= > {



}).finally((a)= > {

  console.log(111)

})

// The state of finally is pending

Copy the code

5.7 Promise. Any

Resolve is the first to come out, only if all Promise objects reject. Promise. Any will print reject. Note the difference with promise.race