【Dart】异步函数

异步函数

  • JavaScript中,异步调用通过Promise来实现
    • async函数返回一个Promise。await用于等待Promise
  • Dart中,异步调用通过Future 来实现
    • async函数返回一个Future,await用于等待Future
  • Future详情
    • https://api.dart.dev/stable/dart-async/Future-class.html

then

import 'package:http/http.dart' as http;
import 'dart:convert';
Future getIPAddress() {
  final urls = 'https://httpbin.org/ip';
  return http.get(urls).then((response) {
    // print(response.body);
    String ip=jsonDecode(response.body)['origin'];
    return ip;
  });
}
  void main(){
    getIPAddress()
        .then((ip) => print('$ip'))
        .catchError((error)=>print(error));
  }

async

import 'package:http/http.dart' as http;
import 'dart:convert';

Future getIPAddress() async {
  final urls = 'https://httpbin.org/ip';
  final response = await http.get(urls);
  String ip = jsonDecode(response.body)['origin'];
  return ip;
}

void main() async {
  try {
    final ip = await getIPAddress();
    print(ip);
  } catch (error) {
    print(error);
  }
}

你可能感兴趣的:(【Dart】异步函数)