在一个映射中,我从一个数据库查询分配一个async/await函数的结果,但我做错了,因为它不工作,我的代码:
arr.map(async(each,i)=>{
await es.getData(each.indexElastic, each[0].attributes.field_query).then(res=>auxJson.queries[i][`results${i}`] = res)
它应该生成一个像这样的json:
{
queries:[
{results0: res},
{results1: res},
{results2: res},
...
]
}
响应是ok的,在地图内部一切都很好,但在地图之外没有任何东西分配给auxJson。我也试着用Promise。all.
怎么了?
我这样做了:
let promises = arr.map((each,i)=>{ return es.getData(each.indexElastic, each[0].attributes.field_query) });
let result = Promise.all(promises).then(res => {
return res.flat(1);
});
result.then(res=>res.map((answer,i)=>auxJson.queries[i][`results${i}`] = answer))
And also doesn't work…
你可以这样做:
let results = await Promise.all(
arr.map(elem => queryDB(elem))
)
也许你应该这样做:
let promises = arr.map((each,i)=>{ return es.getData(each.indexElastic, each[0].attributes.field_query) });
let result = await Promise.all(promises).then(res => {
return res.flat(1);
});
console.log(result);
别忘了把它放到async函数中;)