What is Promise? What are the parameters? how to use?

Noun convention

In general, there are the following noun conventions.

  • Promise (lowercase initials) object refers to “Promise instance object”
  • Promise initial capitalization and singular form for “Promise constructor”
  • Promises is capitalized and pluralized to refer to the “Promises specification”

So let’s talk for a moment

Last June, ES2015 was officially released (that is, ES6, which is its maiden name), in which Promises was included as an official specification. As one of the most important features of ES6, we need to master and understand it thoroughly. In this article, we will explain the basic concepts and usage of Promise from shallow to deep.

What is promise?

  1. mainly used for asynchronous computing
  2. can be queued asynchronous operations, in the desired order of execution, to return the expected results
  3. Promise can be passed between objects and manipulated to help us handle the queue

Why is there a promise?

Synchronization: Suppose you go to a restaurant, find a seat, call the waiter, and the waiter says to you, “Sorry, I’m a “synchronization” waiter, I have to finish serving this table before I can serve you. The table guests have already eaten, you just want a menu, such a small action, but the waiter wants you to wait until someone else’s a big action to complete, to greet you again, this is the problem of synchronization: that is, “the order of delivery of work 1234, must be completed in accordance with the order of 1234”.

Asynchronous: After the time-consuming A-delivered work is given to the system, go on to do the B-delivered work. Wait until the system has finished the previous work, and then continue to do the rest of A’s work through callbacks or events.

The order of completion of AB work is not related to the time order of delivery, so it is called “asynchronous”.

Usage of promise.all

var p1=Promise(function(resolve,reject){
  setTimeout(function(){
    resolve('p1 complete')
  },1000)
})

var p2=Promise(function(resolve,reject){
  setTimeout(function(){
    resolve('p1 complete')
  },2000)
})

var p3=Promise(function(resolve,reject){
  setTimeout(function(){
    resolve('p1 complete')
  },3000)
})

Promise.all([p3,p2,p1]).then(function(res){
  console.log(res);
  // p3, p2, p1 are the order we call ["p3 complete", "p2 complete", "p1 complete"] is the result we return
  // It can be seen that we control the return order of 3 asynchronous requests
})

The use scenario of promise.all is to be able to handle multiple asynchronous requests at the same time and control the order in which they return results. promise.all in any request, there will be no return results.

.then()

  1. receive two functions as parameters, respectively, on behalf of fulfilled (success) and rejected (failure)
  2. .then() returns a new Promise instance, so it can be called in a chain
  3. when the state of the previous Promise changes, . then () according to its final state, select a specific state response function to execute
  4. the state response function can return a new Promise, or other values, no value can be returned we can assume that it returns a null.
  5. if the return of the new promise, then the next level.then () will be executed after the new promise state change
  6. if any other value is returned, then the next level will be executed immediately.then()

.then() inside .then()

  1. because . then() returns or Promise instance
  2. will wait for the inside then() to finish before executing the outside

Promise combined with await asyan wrapper interface API

var token = JSON.parse(localStorage.getItem('userInfo')).remember_token
function http(url, type, data = '') {
 var p =  new Promise((v, b) => {
       $.ajax({
           headers: {
               Authorization: 'Bearer ' + token
           },
           url,
           type,
           data,
           success: (res) => {
               v(res)
           },error:(er)=>{
               b(er)
           }
       })
   })
   return p
}

function getNav(){
   return http('http://***.**.**.***:**/api/menu/info','post')
}
function getList(pageNum,statues,nickname,mobile){
   return http(`http://***.**.**.***:**/api/user?page=${pageNum}&limit=10&status=${statues}&nickname=${nickname}&mobile=${mobile}&`,'get')
}

How does it work?

Usage scenario, Promise encapsulates api interface, Promise for asynchronous operations.
Problem solving, callback multi-domain problem, multiple concurrent requests.

Leave a Reply