【问题标题】:Method running before previous method is finished, Future Async Dart在前一个方法完成之前运行的方法,Future Async Dart
【发布时间】:2021-01-15 07:06:57
【问题描述】:

我的方法 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';
    }
  }

【问题讨论】:

    标签: dart asynchronous async-await


    【解决方案1】:

    您将函数pullTimesAndPrices 标记为async,但未使用await。在调用pullAllData 函数之前使用await 关键字。

    【讨论】:

    • 太棒了,谢谢!我将代码更改为 Future pullTimesAndPrices() async { for (String cryptoCurrency in cryptoAbbreviation) { await pullAllData(cryptoCurrency);处理数据(加密货币); } }
    猜你喜欢
    • 2020-09-28
    • 2019-04-14
    • 2019-08-17
    • 2018-06-01
    • 2021-03-28
    • 1970-01-01
    • 2016-03-13
    • 2021-05-09
    • 2012-07-10
    相关资源
    最近更新 更多