我正在尝试在Promise
函数中创建一个新的数组对象,我还尝试从getUser
函数添加用户参数。
我正在努力将数据放入数组中。
有人能举例说明我如何实现这个目标吗?
感谢。
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);
});
});
}
答案 0 :(得分:2)
首先让我们美化getUser:
function getUser(id){
return connection.query(`SELECT * FROM members WHERE id = ${id} `);
}
Async await也可用于循环,使主循环更优雅:
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;
}
可用作:
getHistory(76)
.then( result => res.json({status:1, result })
.catch( error => res.json({status:500, error });