在Javascript中,您可以使用以下命令将回调转换为承诺:
function timeout(time){
return new Promise(resolve=>{
setTimeout(()=>{
resolve('done with timeout');
}, time)
});
}
这在Flutter中可能吗?
示例:
// I'd like to use await syntax, so I make this return a future
Future<void> _doSomething() async {
// I'm call a function I don't control that uses callbacks
// I want to convert it to async/await syntax (Future)
SchedulerBinding.instance.addPostFrameCallback((_) async {
// I want to do stuff in here and have the return of
// `_doSomething` await it
await _doSomethingElse();
});
}
await _doSomething();
// This will currently finish before _doSomethingElse does.
2条答案
按热度按时间slwdgvem1#
假设我们有一个普通的方法,它只返回一个如下的值:
我们可以像这样直接将它赋值给
Future.value()
,使它成为Future
:wi3ka0sx2#
从this post找到答案。
因此,为了适应上面列出的示例: