我们可以从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中返回值
发布评论