javascript - 有没有办法在 .then() 块中设置数组的状态?
问题描述
`
- 我有一系列点(城市,州)
- 我进行了 fetch 调用以将我的点转换为(经纬度),因此我将结果推送到数组并尝试设置数组的 setState,但是当我使用 console.log(array) 时,我得到了 []。`
if (pointsComplete) {
// for (let i = 0; i < pointsComplete.length; i++) {
for await (let x of pointsComplete) {
if (x.city !== "") {
fetch(
`https://singlesearch.alk.com/na/api/search?&query=${x.city} , ${x.state}&maxResults=1`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: trimble_key,
},
}
)
.then((response) => response.json())
.then((data) => {
pointsCoords.push({
Lat: data.Locations[0].Coords.Lat,
Long: data.Locations[0].Coords.Lon,
position: parseInt(x.position),
});
})
.finally(() => {
setPointsCoordsArray(pointsCoords);
});
}
}
}
解决方案
这对我有用..
if (pointsComplete) {
let promises = [];
for (let x of pointsComplete) {
if (x.city !== "") {
promises.push(
fetch(
`https://singlesearch.alk.com/na/api/search?&query=${x.city} , ${x.state}&maxResults=1`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: trimble_key,
},
}
)
.then((response) => response.json())
.then((data) => {
pointsCoords.push({
Lat: data.Locations[0].Coords.Lat,
Long: data.Locations[0].Coords.Lon,
position: parseInt(x.position),
});
})
);
}
}
Promise.all(promises).then((data) => {
setPointsCoordsArray(pointsCoords);
console.log("______________");
});
}
推荐阅读
- vb.net - 根据datagridview的选定行特定单元格值更改图片框数据
- spring-boot - Gitlab API更新存储库中的现有文件,在rest模板中给出400错误
- javascript - SetTimeout with Promise.resolve 不是输出字符串而是输出字符串的数值,为什么?
- javascript - 使用带有 inject = true 的 HtmlWebpackPlugin 不会缩小 ES6 代码
- java - 计算地图中重复键值的数量
- python - 如何将默认用户插入文件路径python
- php - 闭包表(移动子树)
- php - 如何以相同的形式包含 2 个文件上传,然后将它们插入 PHP 中的 MYSQL 数据库?
- .htaccess - 如何确认正在使用正确的 Robots.txt 文件?
- swift - 代码连接到情节提要时应用程序崩溃