Dart Flutter,帮助我了解 future

Meh*_*bla 2 asynchronous future dart flutter

看这段代码:

class SomeClass{
  String someVariable;
  SomeClass();
  
  Future<String> getData ()  async {
    Response response = await get('http://somewebsite.com/api/content');
    
    Map map = jsonDecode(response.body); // do not worry about statuscode, trying to keep it minimal
    someVariable = map['firstName'];
    return 'This is the first name : $someVariable';
  }
}
Run Code Online (Sandbox Code Playgroud)

现在看主要:

void main(){
  String someFunction() async {
    SomeClass instance = SomeClass(); // creating object
    String firstNameDeclaration = await instance.getData().then((value) => value); 
    return firstNameDeclaration;
  }
}
Run Code Online (Sandbox Code Playgroud)

firstNameDeclaration 当使用 Future 时,就像为什么我必须使用方法来访问字符串对象的情况一样.then(),因为我正在等待函数完成?在网上搜索时,有些人使用.then()其他人不使用,我很困惑。

请帮助我更清楚地了解 Future 和异步函数的整体工作原理。

Tan*_*nuj 6

背景

异步操作使您的程序可以在等待另一个操作完成的同时完成工作。以下是一些常见的异步操作:

  • 通过网络获取数据。
  • 写入数据库。
  • 从文件中读取数据。

要在 Dart 中执行异步操作,可以使用Future类以及asyncawait关键字。

当异步函数调用“await”时,它会被转换为 Future,并放入执行队列中。当等待的 future 完成时,调用函数被标记为准备执行,并将在稍后的某个时刻恢复。重要的区别在于,在此模型中不需要暂停任何线程。

Future 与 async-await

异步函数调用“ await ”时,它会被转换为Future,并放入执行队列中。当等待的 future 完成时,调用函数被标记为准备执行,并将在稍后的某个时刻恢复。重要的区别在于,在此模型中不需要暂停任何线程。

async-await 只是一种定义异步函数并将其结果用于 Future 的声明式方法,它提供了语法糖来帮助您编写涉及 Future 的干净代码。

考虑一下涉及 Future 的这段 dart 代码 -

Future<String> getData(int number) {
  return Future.delayed(Duration(seconds: 1), () {
    return 'this is a future string $number.';
  });
}

main(){
  getData(10).then((data) => {
    print(data)
  });
}
Run Code Online (Sandbox Code Playgroud)

正如您在使用 Futures 时所看到的,当函数返回未来值时,您可以使用 then 回调。如果有单个“then”回调,这很容易管理,但一旦有许多嵌套“then”回调,情况就会迅速升级,例如 -

Future<String> getProductCostForUser() {
  return getUser().then((user) => {
    var uid = user.id;
    return getOrder(uid).then((order) => {
      var pid = order.productId;
      return getProduct(pid).then((product) => {
        return product.totalCost;
      });
    });
  });
}

main(){
  getProductCostForUser().then((cost) => {
    print(cost);
  });
}
Run Code Online (Sandbox Code Playgroud)

当存在多个链接的“then”回调时,代码会变得非常难以阅读和管理。这个问题通过“async-await”解决。上面链接的“then”回调可以通过使用“async-await”来简化,如下所示 -

Future<String> getProductCostForUser() async {
  var user = await getUser();
  var order = await getOrder(user.uid);
  var product = await getProduct(order.productId);
  return product.totalCost;
}

main() async {
  var cost = await getProductCostForUser();
  print(cost);
}
Run Code Online (Sandbox Code Playgroud)

正如您所见,当存在链接的“then”回调时,上面的代码更具可读性和易于理解。

我希望这能解释一些关于“async-await”和 Future 的基本概念和理解。

您可以在此处进一步阅读有关主题和示例的信息