1 回答

TA貢獻1828條經驗 獲得超3個贊
我得到了帶有對象的數組
鑒于該代碼,您不應該這樣做。init
不過,想必您會在某個時候打電話。
但 item1 和 item 2 未定義。我似乎不明白問題是什么。
當您讀取items[0]
將其分配給要導出的對象時,異步函數尚未完成,因此該數組仍然是一個空數組。
您可以item1
用一個getter來替換,該 getter 在您嘗試讀取該屬性時獲取當前值,但這可能仍然會導致競爭條件。items[0]
item1
更好的解決方案可能是導出一個承諾,一旦獲取完成,該承諾將被評估為對象。
顯然,您需要在導出的值上使用then()
or 。await
您不會直接從import
.
const init = async (connection) => {
? ? const items = await connection.collection('collectionName')
? ? .aggregate([{
? ? ? ....
? ??
? ? }])
? ? .toArray()
? ? return {
? ? ? ? all: items,
? ? ? ? item1: items[0],
? ? ? ? item2: roles[1], // whatever roles is
? ? }
};
module.exports = init();
和
const promise = require('../data/items');
const { all, item1, item2 } = await promise;
添加回答
舉報