[英]JavaScript, async/await and promises
I have a problem with async/await and some Promises.我有 async/await 和一些 Promise 的问题。
I have this code.我有这个代码。 It starts here:
它从这里开始:
let valid = await LoadRouter.load(body);
console.log(valid);//showing me Pending Promises
The function is:功能是:
loadGeneratingUnits(data){
let newUGArray = [];
try {
const result = data.map(async (itemGU, index) => {
const checGU = await this.checkDataGu(itemGU.nombre);
if(!checGU){
let newUG = {
generating_unit_name: itemGU.nombre,
description: (!itemGU.descripcion) ? null : itemGU.descripcion,
it_generating_unit_id: (!itemGU.it_unidad_generadora) ? 0 : itemGU.it_unidad_generadora
}
newUGArray.push(newUG);
}
})
return result;
} catch (error) {
throw new Error(error.message)
}
}
This one is where I have the problems这是我有问题的地方
async checkDataGu(guName = null){
if(guName){
return await generatingUnitModel.findOne({
attributes: [
'id',
'generating_unit_name',
],
where: {
generating_unit_name: guName
}
})
}
} }
Any comment about the use of async/await on this code?关于在此代码上使用 async/await 的任何评论?
By making the callback to data.map()
async, data.map()
is now transforming the data into an array of Promises , because the return value of an async function is always a Promise.通过使
data.map()
异步回调, data.map()
现在将数据转换为 Promises 数组,因为异步函数的返回值始终是 Promise。 await
only will wait for a Promise to resolve, not an array of them. await
只会等待 Promise 解决,而不是它们的数组。 You should use Promise.all
for that:你应该使用
Promise.all
:
const result = Promise.all(data.map(async (itemGU, index) => {
const checGU = await this.checkDataGu(itemGU.nombre);
if(!checGU){
let newUG = {
generating_unit_name: itemGU.nombre,
description: (!itemGU.descripcion) ? null : itemGU.descripcion,
it_generating_unit_id: (!itemGU.it_unidad_generadora) ? 0 : itemGU.it_unidad_generadora
}
newUGArray.push(newUG);
}
}))
Now result
is one Promise that will resolve with an array of the values each inner Promise resolved with.现在的
result
是一个Promise,它将使用每个内部 Promise 解析的值的数组来解析。 Ultimately this means your upper let valid = await LoadRouter.load(body);
最终这意味着你的上层
let valid = await LoadRouter.load(body);
should resolve with the array you expect.应该用你期望的数组解决。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.