Monday, 26 September 2016

javascript - Implement promises pattern



I have a function that called with other objects and when my application is loaded, get parameter and the function should wait for call with all of object and then execute so with promises pattern i can ensure all object is loaded but i don't know about count of object and i don't want set timeout for loading.I don't talk about specific technology such as jquery and need algorithm.



Pseudo Code:



      function loadWidget(id){

list.push(id);
//here I should ensure all Widget is loaded


}


in other application i call



    app.loadWidget.add(widget1.id);

.
.
.
app.loadWidget.add(widget2.id);

Answer



If you don't want ready solutions and instead you want to implement all of the algorithms yourself then read the papers referenced in the Wikipedia article: Futures and promises and the specs for Promises/A and Promises/A+.



And to make sure that you're doing it right, read You're Missing the Point of Promises by Domenic Denicola and see the Compliances tests for Promises/A+.




If, on the other hand, you decide that it is not worth it to reinvent the wheel (unless it is for education - in which case by all means reinvent as many wheels as possible) then take a look at RSVP.js, a lightweight library that provides tools for organizing asynchronous code. RSVP.js is used for example by Ember.js.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...