1 回答

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個(gè)贊
我得到了帶有對(duì)象的數(shù)組
鑒于該代碼,您不應(yīng)該這樣做。init
不過,想必您會(huì)在某個(gè)時(shí)候打電話。
但 item1 和 item 2 未定義。我似乎不明白問題是什么。
當(dāng)您讀取items[0]
將其分配給要導(dǎo)出的對(duì)象時(shí),異步函數(shù)尚未完成,因此該數(shù)組仍然是一個(gè)空數(shù)組。
您可以item1
用一個(gè)getter來替換,該 getter 在您嘗試讀取該屬性時(shí)獲取當(dāng)前值,但這可能仍然會(huì)導(dǎo)致競(jìng)爭(zhēng)條件。items[0]
item1
更好的解決方案可能是導(dǎo)出一個(gè)承諾,一旦獲取完成,該承諾將被評(píng)估為對(duì)象。
顯然,您需要在導(dǎo)出的值上使用then()
or 。await
您不會(huì)直接從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;
添加回答
舉報(bào)