实施承诺模式[英] Implement promises pattern

本文是小编为大家收集整理的关于实施承诺模式的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

i具有与其他对象调用的函数,当加载我的应用程序时,获取参数,该功能应等待所有对象的呼叫,然后执行,以便使用承诺模式,我可以确保加载所有对象,但我不don' t知道对象计数,我不想设置加载超时.我不谈论特定技术,例如jquery,需要算法.

伪代码:

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


          }

在其他应用程序中,我致电

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

推荐答案

如果您不想要现成的解决方案,而是想自己实现所有算法,那么请阅读Wikipedia文章中引用的论文:期货和承诺以及的规格Promises/a promises/a+.

并确保您做对了,请阅读您错过了Domenic Denicola的承诺点,请参阅合适的承诺测试/a+.

另一方面,如果您认为重新发明轮子是不值得的(除非是为了进行教育 - 在这种情况下,请尽可能多地重新发明车轮),然后看一下 rsvp.js ,一个轻量级库,提供用于组织异步代码的工具. rsvp.js例如 ember.js .

本文地址:https://www.itbaoku.cn/post/627704.html

问题描述

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);

推荐答案

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.