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

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

问题描述

我的应用程序中有一个 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.

推荐答案

据我目前所理解的 promise,这应该是 100% 没问题的.唯一需要理解的是,一旦解决(或拒绝),即对于延迟对象 - 就完成了.

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

如果你再次调用 then(...) 对它的承诺,你会立即得到(第一个)已解决/被拒绝的结果.

If you call then(...) on its promise again, you immediately get the (first) resolved/rejected result.

额外调用 resolve() 不会有任何效果.

Additional calls to resolve() will not have any effect.

以下是涵盖这些用例的可执行代码片段:

Below is an executable snippet that covers those use cases:

var p = new Promise((resolve, reject) => {
  resolve(1);
  reject(2);
  resolve(3);
});

p.then(x => console.log('resolved to ' + x))
 .catch(x => console.log('never called ' + x));

p.then(x => console.log('one more ' + x));
p.then(x => console.log('two more ' + x));
p.then(x => console.log('three more ' + x));

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

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