我在代码中的很多地方使用了它并且它有效。但在某个地方它没有给出任何错误,也没有给我想要的结果。当我向支持论坛展示我的代码时,他们建议“您错误地使用了 JS 对象/类“Promise”。”
任何人都可以指导我解决我的代码有什么问题吗 这是我的代码示例:
let charity = {};
await Promise.all(
charity = charityData.map(function( data ) {
let address = data.zipCode
let url = "https://maps.googleapis.com/maps/api/geocode/json?&address="+`'${address}'`+"&key=***Google geocoding Key***"; //client's Key
let urlResponse = Backendless.Request.get(url)
// let latitude = urlResponse.results[0].geometry.location.lat;
// let longitude = urlResponse.results[0].geometry.location.lng;
//let updateCharitiesData = {'objectId': data.objectId, 'latitude':latitude, 'longitude':longitude};
return urlResponse;
})
);
return charity;
最佳答案
差不多了。假设 Backendless.Request.[method] 返回一个 promise ,那么按照以下方式做一些事情会更正确:
async function getCharityData() {
const charity = await Promise.all(charityData.map( async function(data) {
const address = data.zipCode;
const url =
`https://maps.googleapis.com/maps/api/geocode/json?&address=${address}&key=***Google geocoding Key***`; //client's Key
const urlResponse = await Backendless.Request.get(url);
return urlResponse;
}));
return charity
}
Promise.all 需要一个数组作为其参数才能正常工作;在这里传递 Array.map 并将返回值分配给慈善机构都可以确保您的 Promise.all 按预期运行,并且返回的数组是已解决的 promise 的数组。
关于javascript - 我正确使用 Promise.all 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70188337/