这里有一个例子MDN,
const colors = fetch("../data/colors.json").then((response) => response.json());
export default await colors;
但是,我有多个常量在单个函数中异步填充:
const _receiversById = {};
const _receiversByServer = {};
const _sequenceReceivers = {}; // name - k-v receivers
const _sequences = {};
// init
async function _fetchAllReceivers(){
// go to the database and copy data into those consts. multiple awaits.
}
我很困惑如何使常量成为函数运行时得到解决的承诺。
我试图将常量分配给不带参数的 Promise 对象
const _receiversById = new Promise();
const _receiversByServer = new Promise();
const _sequenceReceivers = new Promise();
const _sequences = new Promise();
考虑在
.resolve(_receivers...)
函数中调用 _fetch..
,但我非常怀疑它是否有效并且易于调试。
实现这一目标的正确/优雅的方法是什么?
设计
_fetchAllReceivers
,以便它返回您异步填充的四个对象。换句话说,使 _fetchAllReceivers()
返回的 Promise 解析为解析为四个对象(嵌套在包装对象内)的 Promise。
async function _fetchAllReceivers(){
// Make these constants local to the async function
const receiversById = {};
const receiversByServer = {};
const sequenceReceivers = {}; // name - k-v receivers
const sequences = {};
// go to the database and copy data into those consts. multiple awaits.
// ...
// Return (i.e. resolve with) an object that has all the gathered data
return {
receiversById,
receiversByServer,
sequenceReceivers,
sequences
}
}
export default return await _fetchAllReceivers();
在导入方面,您可以执行以下操作:
import obj from './mymodule.mjs'
console.log(obj.receiversById);