【问题标题】:Update Object and push to Array using async and await function? [duplicate]使用异步和等待函数更新对象并推送到数组? [复制]
【发布时间】:2019-09-03 04:09:44
【问题描述】:

我们正在使用 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;
    }
}

【问题讨论】:

  • Got soultion : 使用this找到对解决我的问题很有帮助

标签: node.js express promise


【解决方案1】:

getCounts 返回一个Promise,因此您可以使用.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
}

【讨论】:

  • 我们无法设置getQuestionCounts,我们需要计算出then,或者需要为每个循环更新arr,并将arr 传递给另一个操作。
  • 更新了我的问题以便更好地理解我的要求。
猜你喜欢
  • 2020-09-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-21
  • 2019-08-31
  • 2021-10-06
  • 2014-08-12
  • 2020-08-01
相关资源
最近更新 更多