简体   繁体   English

不了解如何在异步函数中返回对函数数组的答案

[英]Do not understand how to return an answer to a function array within an async function

I'm trying to create a new array object in my Promise function and I'm also trying to add user parameters from the getUser function. 我正在尝试在Promise函数中创建一个新的数组对象,并且还尝试从getUser函数中添加用户参数。

I'm struggling to get the data into the array. 我正在努力将数据放入数组。

Could someone give me an example of how I could implement this? 有人可以给我一个例子,说明如何实现此目的吗?

Thanks. 谢谢。

      var results_array = [];
    return callHistory(76).then((result)=>{
        _.map(result, (item, index) => {
            var obj = JSON.parse(item.params);
            results_array[index] = {
                 id: item.id,
                 status: item.status,
                 timestamp: item.timestamp,
                 from_id:obj.from_id,
                 to_id: obj.to_id,
                 conference: obj.conference,
                 to:"",
                 from:getUser(10)

            };
        });


        res.json({
            status: 1,
            result: results_array
        })
        //return results_array;
    })

function getUser(id){

        return new Promise(function (resolve, reject) {
            connection.query(`SELECT * FROM members WHERE id = ${id} `, function (error, results, fields) {
                if (error) reject(error);
                return resolve(results);
            });
        });

    }

At first lets beautify getUser a bit: 首先让我们美化一下getUser:

function getUser(id){
  return connection.query(`SELECT * FROM members WHERE id = ${id} `);
}

Async await can also be used in loops making your main loop more elegant too: 异步等待也可以在循环中使用,从而使您的主循环也更加优雅:

async function getHistory(index){
  const history = await callHistory(index), result = [];

  for(const call of history){
    const params = JSON.parse( call.params );
    params.to = "";
    params.from = await getUser( 10 /*params.from*/ );

    result.push( params );
  }
  return result;
}

Usable as: 可用作:

getHistory(76)
  .then( result => res.json({status:1, result })
  .catch( error => res.json({status:500, error });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM