数组推送仅适用于回调

问题描述 投票:0回答:1

我正在尝试使用一些猫鼬值更新数组。但它只有在array.push位于回调函数内部时才有效。我尝试过几种方式编码,但在回调之外我总是得到一个空数组。这是一些代码:

let y = [];

Shops.countDocuments({ dt_encerramento: { $gte: jan, $lte: abr }})
   .then(function(os) {
     y.push(os);
   })
   .catch(err => { throw err; });

 console.log(y);

使用async / await:

let y = [];

async function docs() {
   const numDocs = await Shops.countDocuments({ dt_encerramento: { $gte: jan, $lte: abr }}).exec();
   return numDocs;
}

docs().then(function (err,n) { y.push(n); });

console.log(y);

请帮忙。我不知道该怎么办...

arrays node.js count array-push
1个回答
0
投票

我的理解是你错过了一个承诺。

let y = [];

const docs = async () => {
   return await Promise.all(Shops.countDocuments({ dt_encerramento: { $gte: jan, $lte: abr }}).exec());
}

const docsToPush = docs()
y.push(docsToPush)
console.log(y);
© www.soinside.com 2019 - 2024. All rights reserved.