Future.error和投掷飞镖Future有什么区别?

问题描述 投票:1回答:1

我想了解何时在异步函数中使用throwreturn Future.error。在选择一个或另一个时,是否应考虑任何潜在的差异?

我做了一个小测试:

Future testFuture() async {
  return Future.error('error from future');
}

void testThrow() {
  throw('error from throw');
}


Future testFutureThrow() async {
  throw('error from future throw');
}

main() async {
  print('will run test');

  try{
    await testFuture();
  }
  catch(e){
    print(e);
  }

  try{
    testThrow();
  }
  catch(e){
    print(e);
  }


  try{
    await testFutureThrow();
  }
  catch(e){
    print(e);
  }


  testFuture().catchError((e) => print(e));
  testFutureThrow().catchError((e) => print(e));

  print('did run test');
}

他们似乎都以相同的方式工作。这是输出:

will run test
error from future
error from throw
error from future throw
did run test
error from future
error from future throw

我们从该测试中看到的是,从调用者的角度来看,当使用try/catch调用该函数时,代码将同步运行,如果我们使用Future.catchError,则该代码是异步的。但是从功能流程的角度来看,它似乎是相同的。

注意:我起初是为了回答问题。但是后来我意识到我不是在回答而是在做一个问题。

asynchronous dart future
1个回答
0
投票

[我的经验是,如果您想使用myFunc().then(processValue).catchError(handleError);,则应返回Future.error但不要将其抛出。

© www.soinside.com 2019 - 2024. All rights reserved.