【es6】Promise

Promise object definitions:

  For handling asynchronous programming

Features Promise objects

  • State of the object from external influences
  • Once the status change, it will not change any time can get this result

Promise state object

  • pending(processing)
  • fulfilled(succeeded)
  • rejected(Failed)  

Promise to change the state of the object two possible

  • From pendingbecomefulfilled
  • From pendingbecomerejected  

Promise shortcomings object

  • Can not be canceled Promise, it will be executed immediately once the new can not be canceled during;
  • If you do not set a callback function, Promiseinternal error thrown, it does not react to the outside;
  • When in the pendingstate, progress is currently no way of knowing where a stage (beginning or nearing completion).  

Basic usage Promise

  • ES6 predetermined, Promisethe object is a constructor to generate Promiseinstances.  
  • PromiseConstructor parameter is a function , the function of the two parameters, respectively resolveand reject. They are two functions provided by the JavaScript engine, do not have to deploy
  • resolveFunction returns the Promiseobject's state from "not completed" to "success" (i.e., changed from pending resolved), the call is successful asynchronous operation , and the result of the asynchronous operation, to pass out as a parameter
  • rejectFunction returns the Promiseobject's state from "not completed" to "failed" (i.e., changed from pending Rejected), the asynchronous operation failed calls, and asynchronous operation errors may be, as a parameter to pass out
  • const promise = new Promise(function(resolve, reject) {
      // ... some code
    
      if (/* 异步操作成功 */){
        resolve(value);
      } else {
        reject(error);
      }
    });



    By thenthe method are designated resolvedstate and a rejectedcallback status .

  • PromiseAfter the instance generation, you can thenspecify methods resolvedstate and a rejectedcallback status.
  • thenThe method can accept two callback functions as arguments.
           1. The first callback function is Promisethe state becomes the object resolvedinvocation,
           2. The second is the callback Promiseobject's state changes rejectedinvoked.
           3. Among them, the second function is optional and not required to provide. Both functions accept the Promisevalue of the object as a parameter spread.
  • function timeout(ms) {
      return new Promise((resolve, reject) => {
        setTimeout(resolve, ms, 'done');
      });
    }
    
    timeout(100).then((value) => {
      console.log(value);
    });

    In the above code, timeoutthe method returns an Promiseinstance, shows the result after a period of time will occur.
    After a specified time ( msparameter) after the Promisestate of the instance becomes resolved, it will trigger thencallback method binding.

    New Promise will be executed immediately after.

  • let promise = new Promise(function(resolve, reject) {
      console.log('Promise');
      resolve();
    });
    
    promise.then(function() {
      console.log('resolved.');
    });
    
    console.log('Hi!');
    
    // Promise
    // Hi!
    // resolved

    In the above code, Promise performed immediately after the new, the first output is Promise.
    Then, thenthe method specified callback function, the script will be executed in the current sync all tasks executed, so resolvedthe final output.

   

   Pictures lazy loading

  • function loadImageAsync(url) {
      return new Promise(function(resolve, reject) {
        const image = new Image();
    
        image.onload = function() {
          resolve(image);
        };
    
        image.onerror = function() {
          reject(new Error('Could not load image at ' + url));
        };
    
        image.src = url;
      });
    }    

  

   resolveFunction and rejectparameter function problems

    rejectFunction parameters are usually Errorinstances of an object representing error thrown;
    resolvefunction parameters other than the normal value, but also may be another example of Promise

  • With the Promiseobject implements Ajax operations
    const getJSON = function(url) {
      const promise = new Promise(function(resolve, reject){
        const handler = function() {
          if (this.readyState !== 4) {
            return;
          }
          if (this.status === 200) {
            resolve(this.response);
          } else {
            reject(new Error(this.statusText));
          }
        };
        const client = new XMLHttpRequest();
        client.open("GET", url);
        client.onreadystatechange = handler;
        client.responseType = "json";
        client.setRequestHeader("Accept", "application/json");
        client.send();
    
      });
    
      return promise;
    };
    
    getJSON("/posts.json").then(function(json) {
      console.log('Contents: ' + json);
    }, function(error) {
      console.error('出错了', error);
    });

    The above code, getJSONis the encapsulation of the XMLHttpRequest object, for issuing a request for HTTP JSON data, and returns an Promiseobject.
    Note that, in the getJSONinterior, resolvethe function and rejectthe function is called, it has parameters.

    If you call resolvethe function and rejectwith a parameter to a function, then their argument will be passed to the callback function.
    rejectFunction parameters are usually Errorinstances of an object representing error thrown;
    resolvefunction parameters other than the normal value, but also may be another example of Promise, such like this.

     

  • resolveIt is a parameter of the function instance Promise
    const p1 = new Promise(function (resolve, reject) {
      setTimeout(() => reject(new Error('fail')), 3000)
    })
    
    const p2 = new Promise(function (resolve, reject) {
      setTimeout(() => resolve(p1), 1000)
    })
    
    p2
      .then(result => console.log(result))
      .catch(error => console.log(error))
    // Error: fail

    The above code, p1a Promise, becomes 3 seconds later rejected. p2One second after the state change, resolvethe method returns p1.
    Because p2the return is another Promise, leading to p2their own state invalidated by the p1state decision p2states.
    So, behind the thenstatements have become for the latter ( p1).
    It took another two seconds, p1turns rejected, leading the trigger catchmethod specified callback function.

    resolveOr rejectdoes not perform the function parameters of the end of Promise
  • new Promise((resolve, reject) => {
      resolve(1);
      console.log(2);
    }).then(r => {
      console.log(r);
    });
    // 2
    // 1

    The above code calls resolve(1)later, the latter console.log(2)would be executed and will be printed first.
    This is because the Promise is resolved immediately at the end of the current round of the event loop execution, always in sync task late round cycle.

    In general, calling resolveor rejectlater, Promise mission is complete, subsequent operations should be placed theninside the method, and should not be written directly on resolveor rejectbehind.
    Therefore, the best in front of them plus the returnstatements, so there would be no accident.

    In general, calling resolveor rejectlater, Promise mission is complete, subsequent operations should be placed theninside the method, and should not be written directly on resolveor rejectbehind.
    Therefore, the best in front of them plus the returnstatements, so there would be no accident.

  •  

    new new Promise ((Resolve, Reject) => {
       return Resolve (. 1 );
       // the latter statement will not execute 
      the console.log (2 ); 
    })

     

Promise.prototype.then()

  Promise instance has thenmethods, i.e., thenmethods in the prototype object is defined Promise.prototypeon.

  Its role is to add callback function for the state change Promise instance.
  As mentioned above, thenthe first argument of the method is resolveda callback function of the state, and the second parameter (optional) is the rejectedcallback status.

  thenMethod returns a new Promiseinstance (note, not the original Promiseinstance). It can be written using the chain, i.e. thenafter the method then calls another thenmethod.

getJSON("/posts.json").then(function(json) {
  return json.post;
}).then(function(post) {
  // ...
});

Promise.prototype.catch()

  Promise.prototype.catchMethod .then(null, rejection)or .then(undefined, rejection)alias for the specified callback function an error occurs. 

getJSON ( '/ posts.json'). the then ( function (Posts) {
   // ... 
}). the catch ( function (error) {
   // an error occurred while processing a previous callback getJSON and run 
  console.log ( 'error occurs!' , error); 
});

  The above code, the getJSONmethod returns a Promise object, if the state of the object changes resolved, it will call the thenmethod specified callback function;

  If the asynchronous operation throws an error, status changes rejected, will call the catchmethod specified callback function, to deal with this error.

  In addition, the thenmethod specified callback function, if the operation throws an error, will be catchcapture method.

Promise.prototype.finally()

  finallyRegardless of the method used to target Promise final state, the operation will be performed specified. The standard method is introduced ES2018.

promise
.then(result => {···})
.catch(error => {···})
.finally(() => {···});

  In the above code, regardless of promisethe final status after executing thenor catchafter the specified callback function that executes finallythe method specified callback function.

Promse.all()

  Promise.allA method for multiple instances Promise, Promise packaged into a new instance.

  

const p = Promise.all([p1, p2, p3]);

 

The above code, the Promise.allmethod takes an array as a parameter, p1, p2, p3are examples Promise, if not, the following will be called first mentioned Promise.resolvemethod, the parameter into Promise instance, further processing. ( Promise.allMethod parameters may not be an array, but must have the Iterator interface, and each member is returned Promise instance.)

pState by the p1, p2, p3determined, is divided into two cases.

(1) Only p1, p2, p3is turned into a state fulfilled, pthe state will become a fulfilledthis case p1, p2, p3the return value consisting of an array, is passed to the pcallback function.

(2) long p1, p2, p3being there is to be a rejected, pa state becomes rejected, the first case is rejectthe return value of the instance, is passed to the pcallback function.

Promise.race()

  Promise.raceThe method also multiple instances Promise, Promise packaged into a new instance.

const p = Promise.race([p1, p2, p3]);

In the above code, as long as p1, p2, p3in one instance first to change state, pthe state will change accordingly. Promise to return the value of that instance of the first to change, it is passed to the pcallback function.

Promise.raceParameters and methods Promise.allthe same way, if not Promise instance, it will first call the below mentioned Promise.resolvemethod, the parameters into Promise instance, further processing.

Here is an example, if the result is not obtained within the specified time, the state will be changed Promise rejectotherwise becomes resolve.

Promise.resolve()

  Sometimes you need to turn existing objects Promise objects, Promise.resolvemethods to play this role.

const jsPromise = Promise.resolve($.ajax('/whatever.json'));

Surface jQuery code generated deferredobject into a new Promise object.

Promise.resolveEquivalent to the following wording.

Promise.resolve('foo')
// 等价于
new Promise(resolve => resolve('foo'))

Promise.resolveMethod parameters into four cases.

  

(1) is a parameter instance Promise

  If the argument is Promise instance, it Promise.resolvewill not do any modification, is returned unchanged this instance.

(2) the parameter is a thenabletarget

  thenableIt refers to an object having thenan object method, the object such as the following.

let thenable = {
  then: function(resolve, reject) {
    resolve(42);
  }
};

let p1 = Promise.resolve(thenable);
p1.then(function(value) {
  console.log(value);  // 42
});

 

Promise.resolveThis method will be converted to objects Promise objects, then immediately execute thenableobject thenmethods.

The above code, thenableobject thenafter performing the method, the object p1state becomes resolved, so that immediately after the last execution thenmethod specified callback function, the output 42.

(3) has a parameter is not thenan object method, or is simply not an object

  If the parameter value is an original or not having an thenobject method, the Promise.resolvemethod returns Promise a new object state resolved.

const p = Promise.resolve('Hello');

p.then(function (s){
  console.log(s)
});
// Hello

The above example of a new code generation Promise object p.

Because the string Hellodoes not belong to asynchronous operation (determination method is then subject does not have a string method), and returns from a state Promise instance is generated resolved,

Therefore, the callback function will be executed immediately. Promise.resolveMethod parameters, simultaneously passed to the callback function.

(4) no parameters

  Promise.resolve()With no parameters method allows the caller directly returns a resolvedPromise object's state.

  So, if you want to get a Promise objects, more convenient way is to directly call the Promise.resolve()method.

const p = Promise.resolve();

p.then(function () {
  // ...
});

Variable code above pis a Promise object.

It should be noted that immediately resolve()the Promise object is executed at the end of the current round of "event loop" (event loop), rather than when the next round start "event loop".

setTimeout(function () {
  console.log('three');
}, 0);

Promise.resolve().then(function () {
  console.log('two');
});

console.log('one');

// one
// two
// three

The above code, setTimeout(fn, 0)the next round "event loop" started when, Promise.resolve()executed when the current round of "event loop" end, console.log('one')it is immediately executed, and therefore the first output.

Promise.reject()

  Promise.reject(reason)The method also returns a new Promise instance, the state of the instance rejected.

const p = Promise.reject ( 'wrong' );
 // equivalent to 
const = P new new Promise ((Resolve, Reject) => Reject ( 'wrong' )) 

p.then ( null , function (S) { 
  Console .log (S) 
}); 
// wrong

The above code creates an instance of the object Promise p, state rejected, the callback function is executed immediately.

Note that the Promise.reject()parameters of the method, as will be intact rejectreason, the parameters into a subsequent process. This point is Promise.resolveinconsistent methods.

onst thenable = {
  then(resolve, reject) {
    reject('出错了');
  }
};

Promise.reject(thenable)
.catch(e => {
  console.log(e === thenable)
})
// true

The above code, the Promise.rejectmethod parameter is a thenabletarget, after the execution, the back catchparameter method is not rejectout of the "wrong" string, but thenablethe object.

application

  • Load picture
    const preloadImage = function (path) {
      return new Promise(function (resolve, reject) {
        const image = new Image();
        image.onload  = resolve;
        image.onerror = reject;
        image.src = path;
      });
    };

     

  • Generator function of binding with Promise

    function getFoo () {
      return new Promise(function (resolve, reject){
        resolve('foo');
      });
    }
    
    const g = function* () {
      try {
        const foo = yield getFoo();
        console.log(foo);
      } catch (e) {
        console.log(e);
      }
    };
    
    function run (generator) {
      const it = generator();
    
      function go(result) {
        if (result.done) return result.value;
    
        return result.value.then(function (value) {
          return go(it.next(value));
        }, function (error) {
          return go(it.throw(error));
        });
      }
    
      go(it.next());
    }
    
    run(g);

    Generator functions above code gin, there is an asynchronous operation getFoo, it returns is a Promisetarget. Function runto handle the Promiseobject and call the next nextmethod.

Relevant information:

  Promise objects

  

Guess you like

Origin www.cnblogs.com/websmile/p/11507614.html
Recommended