如何使用循环为 `Future.wait()` 提供一个 Futures 列表
我正在使用 Future.wait()
来获取一些数据,如下面的代码所示:
我调用函数 Future.delayed()
在每次调用之间等待 1 秒,因为我将限制设置为每秒 1 个请求
await Future.wait([
Future.delayed(const Duration(milliseconds: 1000))
.then((value) => getPartNumber(1)
.then((value) => addPartToList((value.data)))),
Future.delayed(const Duration(milliseconds: 2000))
.then((value) => getPartNumber(2)
.then((value) => addPartToList((value.data)))),
Future.delayed(const Duration(milliseconds: 3000))
.then((value) => getPartNumber(3)
.then((value) => addPartToList((value.data)))),
Future.delayed(const Duration(milliseconds: 4000))
.then((value) => getPartNumber(4)
.then((value) => addPartToList((value.data)))),
]);
所以我想要做的是使用循环而不是手动重复调用4次
I'm using Future.wait()
to get some data like in the code below:
I call the function Future.delayed()
to wait 1 second between every call because I have a limit set to 1 request per second
await Future.wait([
Future.delayed(const Duration(milliseconds: 1000))
.then((value) => getPartNumber(1)
.then((value) => addPartToList((value.data)))),
Future.delayed(const Duration(milliseconds: 2000))
.then((value) => getPartNumber(2)
.then((value) => addPartToList((value.data)))),
Future.delayed(const Duration(milliseconds: 3000))
.then((value) => getPartNumber(3)
.then((value) => addPartToList((value.data)))),
Future.delayed(const Duration(milliseconds: 4000))
.then((value) => getPartNumber(4)
.then((value) => addPartToList((value.data)))),
]);
So what I wanna do is to use a loop instead of repeating the call manually 4 times
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为什么不能只使用 for 循环并在其间等待 1 秒以不超过速率限制。
这也确保了每秒不会有超过一个请求进入,因为中间的时间是等待的。
或者,如果您希望以与代码中相同的方式处理等待时间,则以下方法也适用:
或者,如果您确实想使用 Future.wait() 来执行此操作(我个人不喜欢),请执行以下操作它:
或
Why can't you just use a for loop and wait 1 second in between to not exceed the rate limit.
This also ensures that no more than one request per second comes in, as the time in between is waited.
Or if you want the waiting time to be handled the same way as in your code, the following also works:
Or if you really want to do it with Future.wait(), which I personally don't like, here's how to do it:
or