1. Before you Promise

1.1 Callback functions

Callback function: if function A is called as an argument to another function B, A is the callback function. Some examples of named callbacks

functionHow many dogs do you have? {fn('A dog')}functionCount dogs {console.log(count)} How many dogs do you have (count dogs) // one dogCopy the code

An anonymous callback

functionHow many dogs do you have? {fn('A dog'How many dogs do you have (function(quantity){console.log(quantity)}) // a dogCopy the code

JQuery is a common example of using callback functions, in this case anonymous callback

$("#btn").click(function(){
    console.log('It's my turn.')})Copy the code

1.2 Callback Hell (Callback Weakness 1)

Callback hell: Refers to a situation where callbacks are so nested that code is hard to read.

let info = []
functionHow many dogs do you have? {fn('A dog')}functionHow many cats do you have? {fn('A cat')}function{info.push(quantity) console.log(info)if(callback){callback()}} (callback){callback()}}function(number of dogs){console.log(number of dogs)function(){how many cats do you have (function(cat count){console.log(cat count) know (cat count)})})})Copy the code

1.3 Do not use Promise, how to solve

Use named functions instead of anonymous ones

let info = []
functionHow many dogs do you have? {fn('A dog')}functionHow many cats do you have? {fn('A cat')}function{info.push(quantity) console.log(info)if(callback){
        callback()
    }
}
functionConsole. log(cat count){console.log(cat count){console.log(cat count)}functionContinue counting (){how many cats do you have (tell you the number of cats)}functionConsole. log(number of dogs){console.log(number of dogs)} How many dogs do you have (number of dogs) // Doesn't seem much better...Copy the code

1.4 Different callback methods need to be memorized separately (Callback disadvantage 2)

readFile('C:\\1.txt'.function(error, data) {// callback in node.js method to read filesif(error) {
            console.log('success')
            console.log(data.toString())
        } else {
            console.log('File reading failed'}}) $.ajax({// callback url in jQuery ajax method:'/2.txt'
    success: function(response) {
        console.log('success')
    },
    error: function(){
        console.log('failure')}})Copy the code

2. The purpose of Promise

Promise is a solution to asynchronous programming that makes more sense and is more powerful than traditional solutions — callback functions and events. It was first proposed and implemented by the community, and ES6 has written it into the language standard, unifying usage, and providing Promise objects natively.

3. How Promise works

3.1 Implementation Principle

ES6 specifies that a Promise object is a constructor that generates a Promise instance. By returning an instance of the Promise object inside the function, you can use the Promise properties and methods for the next step.

functionThe function name () {return new Promise(function(resolve, reject) {
        // ... some code
          ifResolve (value); // call it when the asynchronous operation succeeds, passing the result as an argument}else{ reject(error); // async failure, pass the error as an argument}})}Copy the code

3.2 Call Logic


4. The use of Promise

4.1 Properties and methods of Promise

The promise.prototype property represents the prototype method of the Promise constructor promise.prototype.then () returns a Promise. It needs at most two arguments: a callback to Promise’s success and failure cases. Promise.prototype.catch() returns a Promise and handles rejection cases. Equivalent to the Promise. Prototype. Then (undefined, onRejected) Promise. Prototype. Finally () the finally () method returns a Promise, the execution then (), and the catch (), Will execute the callback function specified in finally. Avoid situations where the same statement needs to be written once in both then() and catch(). Promise. All (iterable) returns an instance of Promise. Resolve is resolved only when all promises in iterable are resolved. Promise.race(iterable) returns a Promise, This is accompanied by a return value that the Promise object resolves or a reason for the rejection error, as long as there is a Promise object “resolve” or “reject” in iterable. Promise.resolve() returns a resolved Promise object with the given value. But if this value is a thenable (namely with then method), will return to the promise of “follow” the thenable object, using its final state (resolved/rejected/pending/hills); If the value passed in is itself a Promise object, that object is returned as the return value of the promise.resolve method; Otherwise return a Promise object with that value as a success status. Promise.reject() returns a Promise object with the reject reason argument, Reason.

4.2 Rewrite the example in callback hell into the form of Promise




















4.3 applications

Load the image as a Promise. Once the load is complete, the state of the Promise changes.

const preloadImage = function (path) {
  return new Promise(function (resolve, reject) {
    const image = new Image();
    image.onload  = resolve;
    image.onerror = reject;
    image.src = path;
  });
};
Copy the code

A combination of Generator functions and Promises (see link for details on Yifeng Ruan’s tutorial)

5. Kill the Promise callbacks

5.1 await

Successful situation

6. Summary

You can use the Promise object to solve callback hell by changing an ordinary function to a form that returns a Promise. Understand the success and failure of the Promise invocation logic, can be flexibly adjusted. Understand the core knowledge, use it first, slowly integrate and absorb the knowledge.

7. Reference links

  • https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
  • http://es6.ruanyifeng.com/#docs/promise
  • https://www.w3cplus.com/javascript/Sexy-Javascript-understand-the-callback-function-with-the-use-of-Javascript-in.html
  • https://juejin.cn/post/6844903446458400775