Futures Processing Methods

I saw a Dart screencast about Futures and how to deal with them. He said that there are two ways to handle some Futures that mix with synchronization code. This is a sample code:

 import 'dart:async'; Map sanitizeParams(Map p) {/*.....*/} Future sendToServer(Map p) {/*.....*/} Future sendParams(Map params) => sendToServer(sanitizeParams(params)); 

Above is a less preferred method, and here is the best code (according to who made the screencast):

 import 'dart:async'; Map sanitizeParams(Map p) {/*.....*/} Future sendToServer(Map p) {/*.....*/} Future sendParams(Map params) => new Future.value(params) .then(sanitizeParams) .then(sendToServer); 

Why does the second prefer?

+4
source share
1 answer

The first reason is readability: sanitizeParams should happen before sendToServer , but it is read in a different order, which should be avoided when working with futures.

A more important reason is that if sanitizeParams throws an exception, then sendParams will not return the future, but will throw it instead, and this makes it difficult for other futures to create it. The second example avoids this by first making the arguments available as Future.value , and then linking other functions to it.

IIRC, this is explained in the screencast.

+5
source

Source: https://habr.com/ru/post/1481208/


All Articles