在异步功能完成之前,Dart For Loop正在退出

时间:2019-06-19 17:21:16

标签: asynchronous networking flutter dart

我一次通过多部分请求将图像上传到服务器。每次发送图像时,我都会收听响应以获取成功消息。

如果返回的JSON["status"] == "Success",我将相应地更新本地数据库以显示该特定图像已同步。该图像在本地更新后,我将成功计数器增加1。

insertImageApi中的for循环结束时,我返回一条成功消息,其中包括成功上传的图像上的数字。

我已成功将所有图像上传到服务器,但是没有我的hack,该函数返回的图像比预期的少一幅。 (例如6之5)

我尝试了3秒的延迟,以便为该函数提供时间以添加最后的成功增量,但这不起作用。

当前,我在return语句中有一个三元运算符,如果成功== 0,则返回0;否则,返回成功+ 1,以补偿最后错过的增量。

我什至尝试在UpdateImageDbApi异步函数之前递增成功。我不太确定我怎么会错过最后一个增量。我看不到如何过早地从此for循环中退出,因为我到处都有等待功能...

_handleApiResponse(var response, SafeguardImage image) async {
    var decodedResponse = json.decode(response);

    if (decodedResponse["status"] == "Success") {
      image.isSynced = 1;
      try {
        successes++; //HACK
        await UpdateImageDbApi().updateImage(image);

      } catch (e) {
        print('failed to update image row in db: ' + e.toString());
      }
    } else if (decodedResponse["status"] == "error") {
      try {
        SafeguardOrder order =
            await QueryOrderDbApi().queryOrder(image.orderId);
        order.isSyncable = 0;
        try {
          var result = await UpdateOrderDbApi().updateOrder(order);
          print("set order #${order.orderId} syncable to 0. result =" +
              result.toString());
        } catch (e) {
          print('unable to update order #${order.orderId} on db: ' +
              e.toString());
        }
      } catch (e) {
        print("unable to query database for images order id: " + e.toString());
      }
    }
  }

  Future<Map<String, dynamic>> insertImageAPI(
      List<SafeguardImage> images) async {

    var start = DateTime.now().millisecondsSinceEpoch;

    for (var image in images) {
      print(image.imageUrl);

      http.MultipartRequest request = await _createMultipartRequest(image);
      print(request.toString());
      try {
        var response = await request.send().timeout(Duration(seconds: 20));
        response.stream.transform(utf8.decoder).listen(
          (response) async {
            print(response.toString());
            await _handleApiResponse(response, image);
          },
        );
      } catch (e) {
        print(e.toString());
        return {
          "error":
              "there was a network error. please try again when you have service"
        };
      }
    }
    Future.delayed(Duration(seconds: 3)); //HACK
    var end = DateTime.now().millisecondsSinceEpoch;
    double duration = (end - start) / 1000;
    print(
        "post images complete: $successes sent. \n it took $duration seconds");
    return {
      "successes": successes == 0 ? 0 : successes + 1, //HACK
      "total_attempted": images.length,
      "duration": duration
    };
  }

我已经用注释标记了这三个骇客。

0 个答案:

没有答案