从Future中返回值

编程入门 行业动态 更新时间:2024-10-10 00:21:32
本文介绍了从Future中返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我们可以从dart中的Future对象返回值还是从中获取值。通过阅读文档,我可以理解我们可以在Future类的then方法中传递一个函数,但是我仍然不知道如何返回该值。

Can we return or get the value from a Future object in dart. By reading the docs i could understand that we can pass a function in then method of Future class, but still i am clueless how can we return the value.

考虑如下伪代码

Int getTotalPay(){ Future<int> pension = getPensionFundAPI(); // a long running api call. don't wait here and call to next api int salary = getTotalSalary(); //wait here till we get the int value received in Future when the above api call completes. int result = salary + pension; print(result);

返回结果; }

return result; }

我知道我可以打电话给Future.then,然后在其中传递回调方法。但是我的目的是要在那时之外返回结果。

i know i can make call to Future.then and pass a callback method in there. but my purpose is to return the result outside of then. same as we do in java and other oops language.

在dart中可能吗?

推荐答案

不可能。就像无法将您80岁的自我带到现在和现在一样:)

It's not possible. Just like bringing your 80 year old self to here and now is not possible :)

但是,您可以编写看起来像可能的代码,但实际上运行着不同的部分在不同时间的单个功能。为此,您需要了解 async 和 await 关键字。

However, you can write code that looks like it's possible, but actually is running different parts of a single function in different times. For that, you need to learn about the async and await keywords.

更多推荐

从Future中返回值

本文发布于:2023-11-25 21:23:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1631398.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:返回值   Future

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!