node.js - 使用异步和等待函数更新对象并推送到数组?
问题描述
我们正在使用async
并await
从另一个函数收集计数,但得到 Promise 问题,我们知道使用then()
但需要更新外部数组/对象。
我们如何才能等待更新forEach
元素并推送到数组?
示例代码:
module.exports = {
getQuestionCounts: function(req, res){ // connected with Routes
var arr = [];
req.data.forEach(element => {
module.exports.getCounts(element).then(function(count){
console.log(count); // getting value
element.count = count;
arr.push(element); // not updating with array
});
});
if(arr.length > 0){ // other operations }
}
getCounts: async function(data){
var count = await Questions.countDocuments({"object":{$elemMatch: {data}}}).then(function(result){
return result;
});
console.log(count); // getting count Fine
return count;
}
}
解决方案
getCounts
返回 aPromise
以便您可以使用.then
回调或async/await
getQuestionCounts: function(req, res){
var arr = [];
// not sure why you're doing this way
module.exports.getCounts(req.data).then(data => {
// data is available only here
console.log(data);
arr.push(data)
// use arr here
})
// arr will be empty
console.log(arr)
}
async/await
getQuestionCounts: async function(req, res){
try {
var arr = [];
var count = await module.exports.getCounts(req.data);
arr.push(count);
} catch (e) {
//handle error
console.error(e)
}
}
注意:所有async
函数返回Promise
首选使用方式module.exports
function someFunc() {
return something;
}
function anotherFunc() {
const result = someFunc()
// do something
return another;
}
module.exports = {
// if you still want to export someFunc
someFunc
anotherFunc
}
推荐阅读
- ffmpeg - 将 MP4 转换为图像序列时,FFmpeg 正在丢帧
- linux - 获取运行命令时修改的文件列表的有效方法是什么?
- sql-server - SQL 处理用户每周在周表日历上设置的假期
- ruby-on-rails - 正则表达式:匹配特定字符
- c# - 无法使用向下箭头键迭代自动完成列表
- symfony - 如何在 routes.yaml 中排除特定路由
- spring - 使用带有 Spring Boot 的 slf4j 登录到数据库
- javascript - TS 错误:类型“未知”不可分配给类型“FunctionComponent”
由于 withRouter - android - 尝试将 Android 应用程序上传到 Play 商店时出现问题
- angular - 'checked' 和 (ngModel) 有什么区别