Preliminary Promise

Promise / Deferred model, is an asynchronous program mode. Other asynchronous programming model, as well as to control async, called flow control.

Today's popular major js library, almost all of varying degrees to achieve the Promise, such as dojo, jQuery, Zepto, when.js, Q, etc., mostly Deferred object is just exposed.

Callback Hell

var fs = require('fs');
fs.readFile('sample01.txt', 'utf8', function (err, data) {
    fs.readFile('sample02.txt', 'utf8', function (err,data) {
        fs.readFile('sample03.txt', 'utf8', function (err, data) {
            fs.readFile('sample04.txt', 'utf8', function (err, data) {

            });
        });
    });
});
复制代码

This nest is abhorrent callback hell.

Promise / A + specifications

  • A promise There are three possible states: waiting (pending), has been completed (fulfilled), has been rejected (rejected)
  • A state can only promise to "complete" the "wait" state, or to "reject" mode, not the reverse transformation, while "done" state and a "reject" state not interchangeable
  • promise must then implement the method (it can be said, then that is the core promise), and then must return a promise, the same promise of then can be called multiple times, and the callback execution order consistent with the order in which they are defined
  • The method then accepts two parameters, the first parameter is a successful callback, the promise of the "wait" state conversion to "done" when the call state, the other is the callback fails to convert the promise by the "wait" state "reject" calls upon states. At the same time, the then accept another incoming promise, also accepts a "class then" the object or method, i.e. thenable object.


Reproduced in: https: //juejin.im/post/5d0b022a51882537b945dac6

Guess you like

Origin blog.csdn.net/weixin_33722405/article/details/93168922