首页 > 解决方案 > 使用异步和等待函数更新对象并推送到数组?

问题描述

我们正在使用asyncawait从另一个函数收集计数,但得到 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;
    }
}

标签: node.jsexpresspromise

解决方案


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
}

推荐阅读