【问题标题】:Check if the request is already done on promise检查请求是否已经按承诺完成
【发布时间】:2020-11-06 01:28:45
【问题描述】:

我在一个文件中有这个函数:

setToStorage() {
    this.settingsService.getSettings().then((settings: any) => {
        localStorage.setItem('const', JSON.stringify(settings));
    });
}

现在在另一个文件中:

if (!localStorage.getItem(STORAGE_ACCOUNT_ATTRIBUTES)) {
        this.accountService.setToStorage();
}
const account = JSON.parse(localStorage.getItem('const'));

问题是在从本地存储中获取const 之前,如何知道setToStorage 是否完成? 因为如果我做JSON.parse(localStorage.getItem('const'))setToStorage() 没有完成,我将有一个空值。请帮我。提前谢谢!

【问题讨论】:

    标签: angular typescript promise angular8


    【解决方案1】:

    这是一个使用函数缓冲区和布尔状态变量的示例。

    当尚未调用 Set 时,我们会将 Get 调用存储到一个数组中并等待。

    当 Set 最终被调用时,我们将解析所有存储的 Get 调用。

    下面的代码是快速创建的,并且在很大程度上是可以改进的。

    • 使用一个实用函数,该函数能够处理对您的函数(Set/Get)的同步调用,并提供函数指针

    function getRndInteger(min, max) {
      return Math.floor(Math.random() * (max - min)) + min;
    }
    
    class LocalStorage {
      constructor() {
        this.valueHasBeenInitialized = false;
    
        // Keep the functions that are waiting for the values to be initialized
        this.functionsKeeper = [];
      }
    
      // Call all the functions that are waiting to be resolved
      unlockKeptFunctions() {
        this.functionsKeeper.forEach(({
          func,
          resolve,
        }) => {
          func.call(this, resolve);
        });
    
        this.functionsKeeper = [];
      }
    
      setToStorage() {
        return new Promise((resolve) => {
          setTimeout(() => {
            console.log('> Resolve setToStorage');
    
            // INSERT THE CONTENT OF THE SET FUNCTION HERE **
    
            this.valueHasBeenInitialized = true;
    
            this.unlockKeptFunctions();
    
            resolve();
          }, getRndInteger(1500, 3000));
        });
      }
    
      /**
       * We want the get to be executed only after a setToStorage
       */
      getFromStorage() {
        return new Promise((resolve) => {
          const func = (r) => {
            setTimeout(() => {
              console.log('> Resolve getFromStorage');
    
              // INSERT THE CONTENT OF THE GET FUNCTION HERE **
    
              r();
            }, getRndInteger(500, 1800));
          };
    
          if (!this.valueHasBeenInitialized) {
            console.log('getFromStorage() is waiting \
     for setFromStorage to be called');
    
            // Wait until the value has been initialized
            return this.functionsKeeper.push({
              func,
              resolve,
            });
          }
    
          func(r);
        });
      }
    }
    
    // Call get and set asynchronously
    (async() => {
      const localStorage = new LocalStorage();
    
      await Promise.all([
        localStorage.getFromStorage(),
        localStorage.getFromStorage(),
        localStorage.getFromStorage(),
        localStorage.getFromStorage(),
        localStorage.setToStorage(),
      ]);
    })();

    【讨论】:

      猜你喜欢
      • 2014-11-24
      • 2015-08-14
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-21
      • 2020-08-28
      相关资源
      最近更新 更多