Fluent callback and multiple request dependency processing

Time:2022-5-5

Only take important notes of flutter

1. Multiple request dependencies are only used to perform other operations after multiple asynchronous operations are completed. The key syntax is:Future.wait[], “wait“The array passed in asynchronous operation will be called only when all the results are returned.then()method
Future.wait([
  //Return results in 2 seconds  
  Future.delayed(new Duration(seconds: 2), () {
    return "hello";
  }),
  //Return results in 4 seconds  
  Future.delayed(new Duration(seconds: 4), () {
    return " world";
  })
]).then((results){
  print(results[0]+results[1]);
}).catchError((e){
  print(e);
});

Execution result: print after 4 seconds

2. Callback hell
A request depends on the result of B request, and B request depends on the result of C request, which is roughly C – > b – > a

The normal practice is probably as follows:

//First, define each asynchronous task separately
Future<String> login(String userName, String pwd){
    ...
    //User login
};
Future<String> getUserInfo(String id){
    ...
    //Get user information 
};
Future saveUserInfo(String userInfo){
    ...
    //Save user information 
}; 


//Call again
login("alice","******").then((id){
 //After successful login, obtain user information through ID    
 getUserInfo(id).then((userInfo){
    //Get user information后保存 
    saveUserInfo(userInfo).then((){
       //Save the user information, and then perform other operations
        ...
    });
  });
})

This way of writing code is simply unbearable

Key methods,Future.then(), this method returns aFuture, it can be called in a chain, so it’s more elegant

login("alice","******").then((id){
    return getUserInfo(id);
}).then((userInfo){
    return saveUserInfo(userInfo);
}).then((e){
   //Perform the next operation 
}).catchError((e){
  //Error handling  
  print(e);
});
    • However, there still seems to be a problem. There is a layer of nesting. What’s the matter?

Key method: can useasync/awaitTo eliminatecallback hell
asyncUsed to indicate that the function is asynchronous, and the defined function will return aFutureObject, you can usethen()Method to add a callback function.
awaitBehind it is aFuture, which means waiting for the asynchronous task to complete, and then going down;awaitMust appear inasyncInside the function.

So be more elegant
task() async {
   try{
    String id = await login("alice","******");
    String userInfo = await getUserInfo(id);
    await saveUserInfo(userInfo);
    //Perform the next operation   
   } catch(e){
    //Error handling   
    print(e);   
   }  
}

** The above example refers to the original address**Highly recommended