首页 > 解决方案 > 在前一个方法完成之前运行的方法,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';
    }
  }

标签: dartasynchronousasync-await

解决方案


您将功能标记pullTimesAndPricesasync但不使用await. 在调用函数之前使用await关键字。pullAllData


推荐阅读