Home > other >  Run multiple asyn function flutter one after one flutter
Run multiple asyn function flutter one after one flutter

Time:11-22

hello I want have to run two functions(Function1() and Function2()) and store value of these returns and run third function. But some time according to condition Function1() or Function2() or both not be run.

if(condition1){
    await Function1();
}
 if(condition2){
    await Function2();
}

await Functon3();

I try as above but Function3() run simultaneously with Function1() or with Function2().

My Function1() code looks like following...

 Future Function1() async {
 
        apiService
        .apiFileUpload()
            .then((value) async {
        ///codes goes here
        }).catchError((error) {
          print('EEEE: '   error.toString());
        });
      
  }

If anything not clear please let me know in the comment section.

CodePudding user response:

Please do not use .then() in combination with async/await. It is technically possible, but it takes some skill to get it right, so why make it hard on yourself. Stick with one way of doing it, use either one or the other. You mixed it up and through a slight oversight, your Function1 does not actually wait on it's result. It just returns, with the function still running in the then block. So you await it, but that does not help.

Since you are using await already, stick with that and remove .then() from your repertoire for now:

Future Function1() async {
  try {
    final value = await apiService.apiFileUpload();
    
    ///codes goes here
  } catch(error) {
    print('EEEE: '   error.toString());
  }
}

CodePudding user response:

You can use await

 Future Function1() async {
   
   try{
    final value =  await apiService
        .apiFileUpload();
    final value2 =  await secondFuntion();
    ///add more and condition on values
    } catch(e){
     .....
    }
  }

CodePudding user response:

from your question you need to tell the compiler to stop on particular task with await and avoid using then function it will never stop your compiler

your future fuction: Future Function1() async {

        apiService
        .apiFileUpload()
            .then((value) async {
        ///codes goes here
        }).catchError((error) {
          print('EEEE: '   error.toString());
        });
      
  }

Modified Future func

Future Function1() async {
 var result = await apiService.apiFileUpload();
 if(result == success){
     // code goes here
 }else{
   //you can show your error here
 }

}

  • Related