多次解决承诺是否安全? [英] Is it safe to resolve a promise multiple times?

查看:65
本文介绍了多次解决承诺是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序中有一个i18n服务,其中包含以下代码:

I have an i18n service in my application which contains the following code:

var i18nService = function() {
  this.ensureLocaleIsLoaded = function() {
    if( !this.existingPromise ) {
      this.existingPromise = $q.defer();

      var deferred = this.existingPromise;
      var userLanguage = $( "body" ).data( "language" );
      this.userLanguage = userLanguage;

      console.log( "Loading locale '" + userLanguage + "' from server..." );
      $http( { method:"get", url:"/i18n/" + userLanguage, cache:true } ).success( function( translations ) {
        $rootScope.i18n = translations;
        deferred.resolve( $rootScope.i18n );
      } );
    }

    if( $rootScope.i18n ) {
      this.existingPromise.resolve( $rootScope.i18n );
    }

    return this.existingPromise.promise;
  };

想法是用户会调用 ensureLocaleIsLoaded 等待承诺得到解决。但鉴于该函数的目的是仅确保加载了语言环境,用户可以多次调用它。

The idea is that the user would call ensureLocaleIsLoaded and wait for the promise to be resolved. But given that the purpose of the function is to only ensure that the locale is loaded, it would be perfectly fine for the user to invoke it several times.

我目前只是存储一个承诺并解决它,如果用户在从服务器成功检索到区域设置后再次调用该函数。

I'm currently just storing a single promise and resolve it if the user calls the function again after the locale has been successfully retrieved from the server.

来自我可以说,这是按预期工作,但我想知道这是否是一个正确的方法。

From what I can tell, this is working as intended, but I'm wondering if this is a proper approach.

推荐答案

因为我了解目前的承诺,这应该100%罚款。唯一需要理解的是,一旦解决(或拒绝),也就是对于一个推迟的对象 - 它就完成了。

As I understand promises at present, this should be 100% fine. Only thing to understand is that once resolved (or rejected), that is it for a defered object - it is done.

如果你应该再次打电话给然后(...),你应该马上得到(首先) )解决/拒绝结果。

If you should call then(...) on it's promise again, you should immediately get the (first) resolved/rejected result.

resolve()的额外调用不会(不应该?)有任何影响。不确定如果您尝试拒绝之前已解决的延迟对象(我怀疑什么都没有)会发生什么。

Additional calls to resolve() will not (should not?) have any effect. Not sure what happens if you attempt to reject a defered object that was previously resolved (I suspect nothing).

这篇关于多次解决承诺是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆