dart - 在前一个方法完成之前运行的方法,Future Async Dart
问题描述
我的方法processData()在pullAllData()完成之前执行,但我需要processData()等到pullAllData()在运行之前完全完成。这导致运行processData()时我的isDownloadSuccessful bool 为 Null 。
Future getCoinData() async {
calculateNumberOfDataPoints();
pullTimesAndPrices();
return timesAndPrices;
}
Future pullTimesAndPrices() async {
for (String cryptoCurrency in cryptoAbbreviation) {
pullAllData(cryptoCurrency);
processData(cryptoCurrency);
}
}
Future pullAllData(cryptoCurrency) async {
String historicalRequestURL =
'$cryptoAPIURL$cryptoCurrency$currency/ohlc?periods=$periodValue&apikey=$apiKey';
http.Response historicalResponse = await http.get(historicalRequestURL);
isPullSuccessful = (historicalResponse.statusCode == 200);
}
void processData(cryptoCurrency) {
if (isPullSuccessful) {
...
} else {
throw 'Problem pulling data';
}
}
解决方案
您将功能标记pullTimesAndPrices
为async
但不使用await
. 在调用函数之前使用await
关键字。pullAllData
推荐阅读
- python - Django中的crsf问题
- python - 带有枚举和 for 循环的代码在第一个字母上给了我重复的结果
- linux - 每个信号量的线程堆栈是多少
- python - web2py:如何在使用 SQLFORM.smartgrid 删除之前执行指令
- c# - 使用表和局部变量中的数据进行查询(C# 和 MS-Access、oledb)
- vba - 我再次收到混合单元格宽度错误
- android - 如何在 OnSuccessListener 中的 recyclerview 适配器中传递侦听器
- ruby-on-rails - 如何清理此 SQL 查询?
- c++ - 在 std::vector 类中使用迭代器
- zend-framework2 - 如何使用 Zend Framework 2 创建多个 where->like()?