gpt4 book ai didi

asynchronous - 用于并行执行的 Flutter 多个异步方法

转载 作者:IT王子 更新时间:2023-10-29 07:21:18 29 4
gpt4 key购买 nike

我仍在为 async/await 模式苦苦挣扎,所以我来这里是想问你一些精确度。

我看到了this page很好地解释了异步/等待模式。我在这里发布了困扰我的例子:

import 'dart:async';

Future<String> firstAsync() async {
await Future<String>.delayed(const Duration(seconds: 2));
return "First!";
}

Future<String> secondAsync() async {
await Future<String>.delayed(const Duration(seconds: 2));
return "Second!";
}

Future<String> thirdAsync() async {
await Future<String>.delayed(const Duration(seconds: 2));
return "Third!";
}

void main() async {
var f = await firstAsync();
print(f);
var s = await secondAsync();
print(s);
var t = await thirdAsync();
print(t);
print('done');
}

在这个例子中,每个async方法被一个接一个地调用,所以main函数的执行时间是6秒(3 x 2秒)。但是,我不明白如果它们一个接一个地执行,异步函数有什么意义。

难道 async 函数不应该在后台执行吗?多个 async 函数不是为了通过并行执行来加快进程吗?

我想我在 Flutter 中遗漏了一些关于异步函数和异步/等待模式的东西,所以如果你能向我解释一下,我将不胜感激。

最好的

最佳答案

使用 Future.wait() 等待多个 Futures 完成如果函数的执行顺序不重要,您可以使用 Future.wait()。

函数快速连续触发;当它们都完成一个值时,Future.wait() 返回一个新的 Future。这个 Future 以一个包含每个函数产生的值的列表结束。

Future
.wait([firstAsync(), secondAsync(), thirdAsyncC()])
.then((List responses) => chooseBestResponse(responses))
.catchError((e) => handleError(e));

或使用异步/等待

try {
List responses = await Future.wait([firstAsync(), secondAsync(), thirdAsyncC()]);
} catch (e) {
handleError(e)
}

如果任何调用的函数以错误完成,则 Future.wait() 返回的 Future 也会以错误完成。使用 catchError() 来处理错误。

资源:https://v1-dartlang-org.firebaseapp.com/tutorials/language/futures#waiting-on-multiple-futures-to-complete-using-futurewait

关于asynchronous - 用于并行执行的 Flutter 多个异步方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55502528/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com