更新对象并使用async和await函数推送到Array? [英] Update Object and push to Array using async and await function?

查看:95
本文介绍了更新对象并使用async和await函数推送到Array?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用asyncawait来从另一个函数收集计数,但是遇到了Promise问题,我们知道要使用then(),但是需要更新外部数组/对象.

We are using async and await to collect the count from another function but getting Promise Issues, We know to use then() but need to update outer array/object.

我们如何等待仍然更新forEach元素并推送到数组?

How can we wait still update forEach element and push to the array?

示例代码:

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返回Promise,因此您可以使用.then回调或async/await

getCounts returns a Promise so you can use .then callback or 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

Note: All async function returns 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
}

这篇关于更新对象并使用async和await函数推送到Array?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆