dart:在对象创建中嵌套等待

时间:2018-04-07 09:20:10

标签: asynchronous async-await initialization dart

以下脚本等待getCategories完成,然后打印数据:

Stream<Category> getCategories() async* {...}

final data = {
  'categories': await getCategories()
    .map((category) => {'id': category.id}).toList()
};

// {categories: [{id: 0}, {id: 1}, {id: 2}]}
print(data);

但是,如果某个类别包含部分列表会发生什么?

final data = {
  'categories': await getCategories()
    .map((category) async => {'id': category.id, 'sections': await category.sections
        .map((section) => {'title': section.title}).toList()
    }).toList()
};

// {categories: [Instance of '_Future', Instance of '_Future', Instance of '_Future']}
print(data);

在这种情况下,脚本会打印Future个实例的列表。我怎样才能优雅地创建具有嵌套等待的对象?

1 个答案:

答案 0 :(得分:1)

也许Future.wait()是您正在寻找的?它将等待期货清单完成:

https://www.dartlang.org/tutorials/language/futures#waiting-on-multiple-futures-to-complete-using-futurewait