【发布时间】:2020-07-23 23:56:32
【问题描述】:
我正在处理相当多的数据,但由于某种原因,页面在发布之前重新加载,并且都可以处理。我需要更新或创建大约 2k 条记录,但是当进程启动时,它会处理一个好块,然后重新加载页面......我知道这与我如何处理 Promises 和我的异步/等待。有人可以提供一些关于我在这里做错了什么的见解吗?
...
// This is called via a button click
const submitData = async () => {
await updateRecords(existData)
await createRecords(newData)
await setCompleteStatus(true) // I think this might be part of the issue. How do I trigger this after the two previous async function complete?
}
// updates records
const updateRecords = async (data) => {
const location = dataSet === 'hfc' ? 'measurements' : 'metrics'
const recordLength = data.length
// If the object exists, update it via API
if (recordLength > 0) {
for (let i = 0; i < recordLength; i += 100) {
const requests = data.slice(i, i + 100).map((row) => {
return puts({ row, location })
.catch(e => console.log(`Error updating record: ${row} - ${e}`))
})
}
}
}
// creates records
const createRecords = async (data) => {
const location = dataSet === 'hfc' ? 'measurements' : 'metrics'
const recordLength = data.length
// If the object exists, update it via API
if (recordLength > 0) {
for (let i = 0; i < recordLength; i += 100) {
const requests = data.slice(i, i + 100).map((row) => {
return posts({ row, location })
.catch(e => console.log(`Error creating record: ${row} - ${e}`))
})
}
}
}
// api put request
const puts = async ({ row, location }) => {
const endpoint = `/api/${location}/record/${row.id}/`
await axios.put(endpoint, row)
}
// api post request
const posts = async ({ row, location }) => {
const endpoint = `/api/${location}/create`
await axios.post(endpoint, row)
}
// I'd like for the page to be redirected after all records have been processed
if (completeStatus) {
window.location.href = '/portal/'
}
...
【问题讨论】:
标签: reactjs async-await es6-promise