Promise/generator/co

Source: Internet
Author: User

---restore content starts---

These three are to solve the callback, the recent Learning KOA framework, the KOA framework is the asynchronous writing into the synchronization, to solve the problem of callback hell, but also easy to control the flow, so find a lot of article study, finally a little sentiment ~ >-<

Look at the name, Promise (commitment), it is easy to think that this should be the result of the asynchronous operation of the commitment, like the database operation, we have to go to find (), find to go after the save (), we promised to find the result after the save, so that the implementation of asynchronous writing variable synchronous writing Promise.then (Db.save () {}) So, we've solved some of the callback function problems.

Or is it more formal to introduce promise: This is an object that is used to pass information about an asynchronous operation.

It's characteristic

1, Promise object represents an asynchronous operation, there are three states Pending (in progress) Resolve (completed) Reject (failed) Only the result of an asynchronous operation can determine the current state
2, Promise Object state change: pending=>resolved, pending=>rejected

Basic usage

var New Promise (function  (resolve, Reject) {    if  (find data succeeded) {        resolve (data);     Else {        reject (err)    }})
// deploying AJAX operations through generator function *main () {    var result = Yield request (' ... ');     var resp = json.parse (result);    Console.log (Resp.value);} function request (URL) {    function(response) {        it.next (response);//parameter plus response, As the value of result, undefined} is returned    )}var it = next (); It.next ();
//resolve callbacks to HellStep1 (function(value1) {Step2 (value1,function(value2) {dothing ...}) })//If you use promise to rewriteQ.fcall (STEP1). Then (STEP2)//step1,2 are asynchronous operations. Then (function() {dosth ...},function(err) {Doerr ...}) . done ();//control the flow with generatorfunction*Longrunningtask () {Try {        varValue1 =yield Step1 (); varvalue2 =yield Step2 (value1); } Catch(e) {s ...}}//This function automatically performs all steps in sequencefunctionScheduler (Task) {setTimeout (function() {        varTaskobj =Task.next (Task.value); if(!taskobj.done) {Task.value=Taskobj.value; Scheduler (Task)‘}}, 0);}

/ After the promise instance is generated, the callback functions of resolve and reject are respectively developed using then method Promise.then (Functioin (data) {    dealwith (data);     function (err) {    handout) (err)    })
//Loading Pictures asynchronouslyfunctionloadimageasync (URL) {return NewPromise (function(Resolve, reject) {varImage =NewImage ();//loading a picture asynchronouslyImage.onload =function() {resolve (image);//The load successfully passes the image to the next function of the promise as a parameter} image.onerror=function() {Reject (NewError (' Could not load image at + ' URL '));    } image.src = URL; })           }
 //  The result of an asynchronous operation is another asynchronous operation  var  p1 = function  Span style= "color: #000000;" > (resolve, reject) {dosomething ();})  var  p2 = function   (resolve, reject) {resolve (P1);  // P2 need to wait for the P1 state to proceed to the next step, equal to the database save needs to wait for the state of find, both of which are two asynchronous operations }) 
 // promise.then  //  db.find (' somefile '  => Save (file. AAA). Then (AAA  => DoSomething (AAA), err  => Console.log (err));  
// Promise.all is used to wrap multiple Promise into one instance var promises = [1, 2, 3, 4, 5, 6, 7].map (function(ID) {    return//  Promise functions }) Promise.all (promises). Then (function(posts) {    do (posts);}). Catch (function(reason) {}
//Generator and Promise//generator for managing processesfunctionGetfoo () {return NewPromise (function(Resolve, Reject) {Resolve (' foo ');//returns a Promise object    })}varg =function*() {    Try{        varFoo = yield Getfoo ();//the iterator does not run hereConsole.log (foo); } Catch(e) {console.log (e); }}//the Simple CofunctionRun (generator) {varit = generator ();//To build an iterator instance    functionGo (Result) {if(result.done) {returnResult.value; }        returnResult.value.then (function(value) {returnGo (it.next (value)); }, function(err) {returnGo (it.Throw(Error)); })‘} Go (It.next ()); Start iterator traversal}run (g)

2, Generator

Generotor can be seen as a state machine, encapsulating the internal state

The Execute generator function returns a Walker object that invokes the next method of the Walker object, allowing the traversed pointer to go down

//generate a Generator objectfunction*ASD () {yield' Joe '; Yield' Chan '; return' Done ';}varASD =ASD (); Asd.next ()//{value: ' Joe ', Done:false}Asd.next ()//{value: ' Chan ', done:false}Asd.next ()//{value: ' Done ', done:true}Asd.next ()//{value:undefined, done:true}

After the yield pause is encountered, the value of the expression after yield is returned as the object
The yield statement has no return value (always returns undefined), and Arg in next (ARG) is treated as the return value of the previous yield statement
 //  One last point on the application  function  *foo (x) { var  y = 2* (yield x);  var  z = yield y;  return  z+y}  var  foo = foo (5 // Span style= "color: #008000;" >{value:5, Done:false}  foo.next () // { Value:nan, Done:false}//Because the return value of yield is undefined  foo.next () // {value:24, Done:false}//incoming parameter as the return value of the last yield  

Synchronous representations of asynchronous operations

function *Loadui () {    showloadingscreen ();    Yield loauiasyncchoromously (); // Asynchronous Operation    // subsequent operations of the asynchronous operation (the original callback function) }var loader = Loadui (); // Load UI Loader.next (); .. // Uninstall UILoader.next ();

//deploying AJAX operations with the generator functionfunction*Main () {varresult = Yield Request ("http://..."); varRESP =json.parse (Result); Console.log (Resp.value);}//Express Ajax in a synchronous mannerfunctionrequest (URL) {makeajaxcall (URL,function(response) {It.next (response);//response as the value of result,  });}varit =main (); It.next ();//Start Traversal iterator

The classic callback Hell

Step1 (function  (value1) {  function(value2) {    dosth ...  });}); // rewrite the above code with promise Fcall (STEP1)  . Then (STEP2)  . Then (function  (value2) {    do ...   function (Error) {    Doerr  })  . Done ();



Generator function control code run flow
function*Longrunningtask(){Try{var value1= YieldStep1();var value2= YieldStep2 (Value1;  //do ... } catch  ( e) { Doerr }}//synchronization control Flow 

Scheduler(Longrunningtask());functionScheduler(Task){SetTimeout(function(){var taskobj= Task.Next(Task. value if  (!taskobj.done" {task.value = taskobj.value scheduler;  }0;}  

Reference

http://es6.ruanyifeng.com/#docs/generator

Promise/generator/co

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.