简体   繁体   中英

Chaing async method on Dart

I have following class.

class Element {
  Future<Element> findById(var id)async {
     await networkRequest();
     return this;
  }

 Futute<Element> click() async {
    await networkRequest();
    return this;
 }
}

I want to achieve the something like.

main() async {
  var element = Element();
  await element.findyById("something").click();
}

But I'm not able to do so because element.findById() returns future. How can I chain these async methods.

While there's no special syntax to chain futures, there are two semantically equivalent ways to do what you want:

1) Two separate await calls:

await element.findById("something");
await click();

2) Chaining with then :

await element.findById("something").then(() => click());

Use this,

await (await Element().findById("1")).click();
final el = await element.findyById("something");
await el.click();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM