【问题标题】:Does the await keyword in Dart automatically handle data dependency?Dart 中的 await 关键字是否会自动处理数据依赖关系?
【发布时间】:2018-07-05 13:43:52
【问题描述】:

例如在下面的代码中

var Cake thisCake = new CheeseCake();
thisCake = await fetchGreenTeaCakeOnline();
if (thisCake.isCheeseCake) {
    print('This is still a cheese cake.')
} else {
    print('The cake is updated')
}

thisCake原本是cheeseCake的实例,会被异步赋值为GreenTeaCake的实例。 if 子句会等待await 赋值完成后执行,还是会忽略thisCake 的数据依赖关系执行?

更新:感谢Günter Zöchbauer,修复了语法错字

【问题讨论】:

    标签: asynchronous async-await dart


    【解决方案1】:

    await 等待 Future 完成。 在您的示例中,thisCake 将获得分配的 Future,然后 await 等待它完成。

    你可能更想要

    thisCake = 等待 fetchGreenTeaCakeOnline()

    这样await 等待Future 完成并将期货值分配给thisCake

    【讨论】:

    • 谢谢 Günter,这是一个错字。我的意思是thisCake = await fetchGreenTeaCakeOnline(),我在文档中阅读了更多内容,并认为它处理了数据依赖关系。
    • 不确定“数据依赖”是什么意思。您可以使用fetchGreenTeaCakeOnline().then((thisCake) { if (thisCake.isCheeseCake) { 查看await 在幕后所做的事情。当Future 完成时,将执行传递给then(...) 的回调并传递值。 await 只是使语法更好。
    • 好的,谢谢,我想你已经回答了这个问题。通过数据依赖,我的意思是 if 子句会在未来完成之前执行。
    • 好的,await 的作用基本上就这些了,以确保await 之后的代码在执行下面的代码之前完成。您需要确保 fetchGreenTeaCakeOnline() 内某处的整个 Futures 链也在等待,否则异步执行仍然可以在顶级 await 无法等待的情况下执行。
    猜你喜欢
    • 2015-06-08
    • 2015-05-11
    • 1970-01-01
    • 2019-12-02
    • 2021-10-18
    • 1970-01-01
    • 2018-06-24
    • 2018-05-17
    • 1970-01-01
    相关资源
    最近更新 更多