javascript - 在 for 循环中处理返回承诺结果
问题描述
我是 JS 和 Vue 的新手。
我有 100 行 url 发送到后端。我使用 for 循环调用 api,数据是每一行。
<template>
<table>
<thead>
<tr>
<th>No.</th>
<th>Url</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr v-for="(post, index) in posts">
<td>{{ index + 1}}</td>
<td>{{ post.url}}</td>
<td class="classStatus(post.status)">{{ post.status}}</td>
</tr>
</tbody>
</table>
脚本:
const apiUrl = 'example.com/api/createPost'
for (post of this.posts) {
// Sent only posts with status READY or FAIL
if (post.status === STATUS_SUCCESS) {
continue;
}
// Call api to process post one by one
this.apiService(apiUrl, post)
.then(result => {
post.status = STATUS_SUCCESS
}).catch(err => {
post.status = STATUS_FAIL
})
}
它适用于单个帖子(api 调用 1 次):
- 1 个有效 url(插入后端)-> post.status 更新为 STATUS_SUCCESS
- 1 个无效的 url(在后端控制台中抛出异常)-> post.status 更新为 STATUS_FAIL
但是,如果有多个帖子:
- 有效之前的行无效 url => 两行 post.status 更新为 FAIL
- 在无效 => 状态更新正确之前行有效 url ,但我只检查了 1 次网络调用 API。
你能帮我知道为什么会有多个帖子发生吗?
- 如果在有效数据之前调用了无效数据,我不知道为什么它们都会失败
- 我的脚本是反模式吗?(在循环内调用 API)
解决方案
推荐阅读
- javascript - 将值设置为条纹元素
- ios - 如何以及在哪里找到 Phrase OTA 下载的翻译文件?
- r - R:根据函数的返回值将布尔列添加到 data.table,该函数评估来自不同 data.table 的两列
- c - “__tmainCRTStartup() at 0x4013c1”没有可用的源
- wpf - 将 Powershell WPF 对话定位在右下角
- c - 在二维数组中,如何根据某个元素的条件移动一行?
- react-native - 添加 efr=1 后反应原生 firebase 动态链接不起作用
- mule - 如何在 DataWeave 2 转换脚本中使用配置参数?
- javascript - 递归返回 0 而不是 2?
- image - 为什么我的加载图像和 screen.blit 功能不起作用?