【问题标题】:Async IIFE module - cache result and do not return promises in further requires异步 IIFE 模块 - 缓存结果并且在进一步需要时不返回承诺
【发布时间】:2019-03-09 07:43:21
【问题描述】:

考虑拥有以下文件:

index.js

(async () => {
  const iife = await require('./asyncIIFE');
  console.log('[index.js]', iife);

  require('./module');
})();

asyncIIFE.js

module.exports = (async () => 'Testing async IIFE')();

模块.js

const iife = require('./asyncIIFE');

(() => {
  // Should print Testing async IIFE
  console.log('[module.js]', iife); // Promise

  iife.then(text => console.log('[module.js]', text)); // Testing async IIFE
})();

主要思想是计算入口点(index.js)中的所有值,然后使用它们而不在其他文件中重新计算。第一个 require('asyncIIFE') 应该是异步的,下一个应该立即返回值。

应该是这样的:

  1. 需要 index.js 中的所有异步模块并等待结果

  2. 所有进一步要求其他文件中的相同异步模块(例如。 module.js) 应该立即返回值而不需要 await/.then()

代码输出:

[index.js] Testing async IIFE
[module.js] Promise { 'Testing async IIFE' }
[module.js] Testing async IIFE

简而言之,我想摆脱 module.js 文件中的承诺并获取缓存值。我怎样才能做到这一点?

【问题讨论】:

  • 我会将计算为参数的值发送到 非异步 模块。 require('./module')(iife); 并创建一个闭包以将参数注入您的模块中。
  • Ew。函数不应该在第一次调用时返回一种类型的东西,然后在第二次调用时完全返回其他类型的东西。相反,让它始终返回承诺。只需不要在创建 Promise 后重新创建它。
  • 是的,这肯定会有所帮助。但是,我想知道是否有其他方法可以做到这一点。将来我可能需要嵌套模块,并且将对象传递给所有这些会很痛苦。我也可以在异步闭包中要求它们,但我认为这不是一个好主意(要求应该是顶级的?)
  • 我同意@KevinB,函数应该总是返回相同类型的结果。但是,您可以使用 once 函数将结果缓存在 Promise 中,并在后续调用中立即返回已解决的 Promise。
  • 这里是一个 once 函数的例子。 davidwalsh.name/javascript-once

标签: javascript node.js async-await es6-promise es6-modules


【解决方案1】:

当您在 module.js 文件中导入 async.js 时,您并未解析函数。

module.js

const iife = require('./async');

(async () => {
  // Should print Testing async IIFE
  console.log('[module.js]', await iife); // Promise
  // Notice how I added the await keyword, that's there to resolve the promise
  // Function has also changed to asynchronous to use await.

  iife.then(text => console.log('[module.js]', text)); // Testing async IIFE
})();

基本上,您并没有解析您导入的文件,并且由于该文件返回一个承诺,您的控制台会记录一个承诺。

index.js

(async () => {
  const iife = await require('./async');
  console.log('[index.js]', iife);

  require('./module');
})();

async.js

module.exports = (async () => 'Testing async IIFE')();

module.js

(async () => {
  const iife = await require('./async');
  console.log('[index.js]', iife);

  require('./module');
})();

顺便说一句,我稍微更改了文件名。希望这不会影响任何事情。

【讨论】:

  • 我明确表示不想使用 await 但感谢您的回答。
猜你喜欢
  • 2019-10-20
  • 1970-01-01
  • 2022-01-26
  • 2019-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-16
相关资源
最近更新 更多