简体   繁体   English

具有承诺和关闭范围的延迟加载

[英]Lazy loading with promise and closure scope

I have a need to make async and lazy loading module to fetch some config values. 我需要制作异步和延迟加载模块以获取一些配置值。 Is there some limitation with closure variable scoping in relation to promises? 与承诺相关的闭包变量作用域是否存在某些限制?

Given the following module that defines a loader function that performs the async loading with promises and stores the config to module scope in order to implement lazy loading and thus avoid loading the config unnecessary each time. 给定以下模块,该模块定义了一个加载器函数,该函数执行带有promise的异步加载并将配置存储到模块范围中,以实现延迟加载,从而避免每次都不必要地加载配置。

const configModule = () => {
  let config;

  const loader = () => {
    return new Promise((resolve, reject) => {
      if(!config) {
        setTimeout(() => {
          const loadedValues = {foo: 'this be config', bar: 'OK?'};
          console.log('config loaded', loadedValues);
          resolve(loadedValues);
        }, 1);  
      }
      else {
        console.log('config already loaded');
        resolve(config);
      }
    }).then(res => {
      console.log('loader then', res);
      config = res;
      return config;
    })
  };

  return {
    loader: loader
  };
};

With the following client code, the config is loaded but always freshly, ie it is not cached, lazy-loading not working. 使用以下客户端代码,该配置将被加载,但始终是全新的,即它不被缓存,延迟加载不起作用。

const cc = configModule();

cc.loader().then(result => {
  console.log('1', result);
});
cc.loader().then(result => {
  console.log('2', result);
});

Is there something I'm missing with closure scopes and promises here? 在这里我缺少闭包范围和承诺吗? Or is this approach even feasible? 还是这种方法可行? What is the alternative? 有什么选择?

Your caching module is working right. 您的缓存模块运行正常。 But in your test you're making both "API calls" immediately. 但是在测试中,您将立即进行两个“ API调用”。 So both cc() calls will test if (!config) before the other one updated it. 因此,两个cc()调用都将在另一个if (!config)更新之前测试它if (!config) As soon as one call is able to return with a value and update the config , the cache will start working. 只要一个调用能够返回一个值并更新config ,缓存就会开始工作。

 const configModule = () => { let config; const loader = () => { return new Promise((resolve, reject) => { if (!config) { setTimeout(() => { const loadedValues = { foo: 'this be config', bar: 'OK?' }; console.log('config loaded', loadedValues); resolve(loadedValues); }, 1); } else { console.log('config already loaded'); resolve(config); } }).then(res => { console.log('loader then', res); config = res; return config; }) }; return { loader: loader }; }; const cc = configModule(); cc.loader().then(result => { console.log('1', result); }); setTimeout(() => cc.loader().then(result => { console.log('2', result); }), 100); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM