Is it safe to resolve a promise multiple times?

前端 未结 7 842
旧时难觅i
旧时难觅i 2021-01-31 06:33

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

var i18nService = function() {
  this.ensureLocaleIsLoaded = function() {
    if( !th         


        
7条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 07:36

    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.

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

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

提交回复
热议问题