Promise implements lazyman., promise implements lazyman

Source: Internet
Author: User

Promise implements lazyman., promise implements lazyman

First, please refer to the implementation of setTimeout by netizens:

Function _ LazyMan (name) {this. tasks = []; var self = this; var fn = (function (n) {var name = n; return function () {console. log ("Hi! This is "+ name + "! "); Self. next () ;}}) (name); this. tasks. push (fn); setTimeout (function () {self. next () ;}, 0); // start the task in the next event loop}/* event scheduling function */_ LazyMan. prototype. next = function () {var fn = this. tasks. shift (); fn & fn () ;}_ LazyMan. prototype. eat = function (name) {var self = this; var fn = (function (name) {return function () {console. log ("Eat" + name + "~ "); Self. next ()}) (name); this. tasks. push (fn); return this; // implement chained call} _ LazyMan. prototype. sleep = function (time) {var self = this; var fn = (function (time) {return function () {setTimeout (function () {console. log ("Wake up after" + time + "s! "); Self. next () ;}, time * 1000) ;}) (time); this. tasks. push (fn); return this;} _ LazyMan. prototype. sleepFirst = function (time) {var self = this; var fn = (function (time) {return function () {setTimeout (function () {console. log ("Wake up after" + time + "s! "); Self. next () ;}, time * 1000) ;}) (time); this. tasks. unshift (fn); return this;}/* encapsulate */function LazyMan (name) {return new _ LazyMan (name);} LazyMan ('Hank '). sleepFirst (5 ). sleep (10 ). eat ('dinner ')

Analysis:

SetTimeoutSimulated thread, There isEvent processing queue (This. tasks)And then each event callsEvent scheduling function (Next)Each time the business logic is defined through the closure functionFn,Fn executes the next function after processing its own business internally.

As a result, the promise is very suitable for processing services that contain Asynchronization and have certain blocking.The implementation idea is completely different..

First, consider:

Lazyman contains a chain call, so each subtask returns this; this program supports the task priority, then two Promise objects throughout the entire audience are required: first, the general order promise; second, the insertion sequence is promise, and the insertion sequence is blocking the normal sequence. The Code is as follows:

Function _ lazyman (name) {this. orderPromise = this. newPromise (); // defines the ordered promise object this. insertPromise = this. newPromise (); // defines the insert promise object this. order (function (resolve) {console. log (name); resolve () ;}} _ lazyman. prototype = {/* instantiate the promise object factory */newPromise: function () {return new Promise (function (resolve, reject) {resolve () ;})}, order: function (fn) {var self = this; this. orderPromise = this. orde RPromise. then (function () {return new Promise (function (resolve, reject) {// if there is insertPromise, blocking orderPromise. self. fir? Self. insertPromise. then (function () {fn (resolve)}): fn (resolve) ;})}, insert: function (fn) {var self = this; this. fir = true; this. insertPromise = this. insertPromise. then (function () {return new Promise (function (resolve, reject) {fn (resolve) self. fir = false ;})}, firstTime: function (time) {this. insert (function (resolve) {setTimeout (function () {console. log ('wait' + time +'s, other logic '); resolve () ;}, time * 1000 )})
Return this;}, eat: function (something) {this. order (function (resolve) {console. log (something + '~~ ') Resolve ();})
Return this;}, sleep: function (time) {this. order (function (resolve) {setTimeout (function () {console. log ('sleep '+ time + s'); resolve ()}, time * 1000 );})
Return this ;}} // API encapsulation. Function lazyman (name) {return new _ lazyman (name);} // call test lazyman ('roryw '). firstTime (1 ). sleep (2 ). firstTime (3 ). eat ('dinner '). eat ('Breakfast '); // pop-up: // wait 1 s, other logic // wait 3 s, other logic // RoryWu // sleep 2 s // dinner ~~ // Breakfast ~~

 

Note that the business logic of each task is implemented in the form of callback functions. There are two internal APIs:

1 this. order (function (){...})

2 this. insert (function (){...})

Pay attention to the following points:

1. the business logic function of each task is the callback function that is passed to the corresponding API,Execution siteIn It.

2.Execution rightThe task function itself is passed through parameters, such as fn (resolve). After each task function executes its own business logic, it uses resolve () change the Promise object status to Resolved (Other: rejected pending ).

The priority of three connected APIS is implemented through a this. the status value of fir is used to determine whether a promise object is inserted. If yes, it will change the occurrence time of fn: insertPromise. then (function () {fn (resolve )})

 

Through the above implementation, I will summarize the following: when designing a program, I first think about the approximate structure of the program, and then I will write it at the beginning, so that the big idea will not run, and then I will soon write it out.

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.