Curious behavior of async/await

时间:2019-05-19 04:04:24

标签: javascript reactjs ecmascript-6 async-await google-chrome-devtools

I know the proper way to use await is warring it up with async function.

I found this below approach while surfing online. Initially, I thought it will not work. But when I run this in my chrome console it surprises me. It works.

var _response = await (await fetch('https://reqres.in/api/users?page=2').then(res => res.json()));
console.log(_response);

But when I tried this approach in my Rectjs project it doesn't work.

Throws me below error.

unknown: Unexpected token (1:22)

1 | var _response = await (await fetch('https://reqres.in/api/users?page=2').then(res => res.json()));

I have also tried in a lot of online es6 compilers such as https://repl.it/languages/babel It won't work. It only works in my chrome console (chrome 74).

Someone help me out to understand this behavior clearly.

Thanks in advance.

2 个答案:

答案 0 :(得分:3)

The behavior you describe is specific to Chrome's DevTools.

https://bugs.chromium.org/p/chromium/issues/detail?id=658558

It looks like they added it in response to a feature request from the community.

答案 1 :(得分:-1)

您可以将异步呼叫包装在异步IIFE中,如下所示:

void _signInWithPhoneNumber(String _code) async {

final AuthCredential credential = PhoneAuthProvider.getCredential(
  verificationId: _verificationId,
  smsCode: _code,
);
final FirebaseUser user = await _auth.signInWithCredential(credential);
if (user != null) {
  phone = user.phoneNumber;
  fid = user.uid;
  saveLogin(context);
} else {
  _showErrorDialog("User Verification Error!");
}
  }