有没有办法等待传递给函数的数据,以便 export/import 可以使用等待的数据?

Is there a way to await data passed into function so the awaited data is available for export/import?

我想从后端异步加载数据并将一些参数应用到 thunk 中,以便可以将记忆函数导入我代码的其他区域。因为目前不允许在顶层等待,所以我等不及将值传递给导出的函数。

比如我有这个功能:

const aFunction = (someData) => (props) => {
  // do stuff
}

const someDataFromApi = await getData(); // <-- will not work: top level await not allowed 

const appliedAFunction = aFunction(someDataFromApi);

export { appliedAFunction, aFunction};

然后我会让应用的函数随时可以导入到任何地方(或者当然也可以使用非应用的版本):

import {appliedAFunction, aFunction} from './aFunction'

const cProcess = () => {
  const props = { a: 'foo' };
  appliedAFunction(props)
}

const dProcess = async () => j
  const data = await getData();
  const props = {b: 'bar'};
  aFunction(data)(props)
}

是否有 accepted/recommended 异步应用参数的方法以便它可用于 export/import?

这是我想出的解决方案,它允许我导出已传递承诺值的函数。它与在顶层等待的答案不同,但它的工作原理相同,允许传递和存储异步检索的值,以便在调用导出函数时可用。

这个函数允许我将 promise 作为参数预加载,这意味着我可以在 promise 解析之前导出函数。

const passToThunkPromiseAsArg = (func: Function) => (
  promise: Promise<any>
) => {
  return (...args) => {
    return promise
      .then((resolvedValue) => {
        return func(resolvedValue)(...args);
      })
      .catch((e) => {
        // you might want to resolve errors differently
        return func(null)(...args);
      });
  };
};

例子

在导出之前,我向我的函数传递了一个 promise of a value 而不是 value:

// ...
const promiseOfValue: Promise<any> = extremelySlowCalculation();
const appliedAFunction = passToThunkPromiseAsArg(aFunction)(promiseOfValue);

export default {aFunction, appliedAFunction}

然后在其他文件中我可以调用并等待或 Promise.then appliedAFunction:

import {appliedAFunction} from './aFunction'

const cProcess = async () => {
  const props = { a: 'foo' };
  const b = await appliedAFunction(props)
}

cProcess 调用 appliedAFunction 时,promise 很可能已经解决,因此在大多数情况下,当 b 获得解决值时没有实际延迟。在极少数情况下,它尚未解决,函数将等待值。