我有一个Button,单击它会发出POST请求。在等待响应时,我有一个正在加载动画。但是,现在我希望此按钮不仅发出1个帖子请求,我还希望它通过单击1来进行100个帖子请求
我的按钮
<Form>
<Form.Group>
<Button variant='success' className='button' onClick={handleClick} id='create'>Create Sales Order</Button>
</Form.Group>
</Form>
等待API调用时我的加载器
<BeatLoader
css={override}
size={30}
// size={"150px"} this also works
color='#b51a82'
loading={isLoading}
/>
这是handleClick函数,当按下按钮时会调用
async function handleClick (event) {
switch (event.target.id) {
case 'create':
setLoading(true)
break
case 'delete':
// code for delete case
break
default:
console.log('click didnt work')
}
}
我的useEffect Hook。在此挂钩中,我尝试将createSalesOrder函数的内容放入循环中,该循环无效,因为它将破坏我的加载动画(加载动画不会停止)
useEffect(() => {
async function createSalesOrder () {
const res = await axios.post('http://localhost:5000/')
console.log(res)
setValue([...value, res.data])
return (res)
}
if (isLoading) {
createSalesOrder().then(() => {
setLoading(false)
})
}
}, [isLoading])
答案 0 :(得分:2)
您可以使用Promise.all
等待一个或多个诺言完成。它会返回一个“承诺”,即“包装”所有其他承诺,这些承诺将在所有承诺均已解决时解决,或者如果其中一个承诺被拒绝,则立即拒绝。
如果您想等待所有的诺言完成,即使某些诺言被拒绝,也可以使用Promise.allSettled
useEffect(() => {
async function createSalesOrder () {
const res = await axios.post('http://localhost:5000/')
console.log(res)
setValue([...value, res.data])
return (res)
}
if (isLoading) {
const finished = _ => setLoading(false);
// Wait for all of the sales orders to finish
Promise.all(
// Create an array of 100 promises:
// Quickly create an array with 100 entries
[...Array(100).keys()].map(
// For each entry, submit a request to create a sales order
// and return a promise
createSalesOrder
)
).then(
// When all of the promises have resolved, end your animation:
finished,
// Make sure you stop the animation even if an error occurred:
finished
);
}
}, [isLoading])
此外,请记住,承诺将按照它们从服务器返回的顺序进行解决/拒绝,而不必按发送的顺序进行。这意味着您创建的第一个顺序很可能会在中间某个位置被解析,您创建的最后一个顺序将首先被解析,依此类推,并且如果您重复逻辑,则它们的解析顺序也很有可能。每次都会不同。