Javascript 不了解如何在异步函数中返回函数数组的答案
我正在尝试在我的Javascript 不了解如何在异步函数中返回函数数组的答案,javascript,node.js,express,async-await,es6-promise,Javascript,Node.js,Express,Async Await,Es6 Promise,我正在尝试在我的Promise函数中创建一个新的数组对象,并且还尝试从getUser函数中添加用户参数 我正在努力将数据放入阵列中 有人能给我举个例子,说明我如何实现这一点吗 谢谢 var results_array = []; return callHistory(76).then((result)=>{ _.map(result, (item, index) => { var obj = JSON.parse(item.
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);
});
});
}
首先让我们稍微美化一下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 });
首先让我们稍微美化一下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 });
我没有在nodej上使用lodash的好处…可能重复您在哪里使用
async
/wait
?我没有在nodej上使用lodash的好处…可能重复您在哪里使用async
/wait
?“首先让我们美化一下getUser”-没有<代码>连接。查询接受回调。@可能是bergi。例如,如果没有通过回调,mongodb驱动程序将返回一个承诺。这取决于实现(而且看起来它对OP有效)啊,好的。不过,在这种情况下,您也不应该使用async
/wait
,只需编写函数getUser(id){return connection.query(`SELECT*FROM members WHERE id=${id}`);}
“首先让我们稍微美化一下getUser”-否<代码>连接。查询接受回调。@可能是bergi。例如,如果没有通过回调,mongodb驱动程序将返回一个承诺。这取决于实现(而且看起来它对OP有效)啊,好的。不过,在这种情况下,您也不应该使用async
/wait
,只需编写函数getUser(id){return connection.query(`SELECT*FROM members,其中id=${id}');}