在async函数中链式调用await 报错:Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
代码
class ApiClient{
constructor(){
this.value=null
}
async firstMethod(){
this.value=await fetch('url-1').then(r=>r.json)
return this
}
async secondMethod(){
this.value=await fetch('url-2').then(r=>r.json())
return this
}
}
const client =new ApiClient()
const result=await client.firstMethod().then( c=> c.secondMethod())
报错信息
正确方式
class ApiClient {
constructor() {
this.value = null;
}
async firstMethod() {
this.value = await fetch('/first-url').then(r => r.json());
return this;
}
async secondMethod() {
this.value = await fetch('/second-url').then(r => r.json());
return this;
}
}
// 使用方式
async function result() {
const client = new ApiClient();
const result = await client.firstMethod().then(c => c.secondMethod());
}
提示!!!
async返回的是一个promise,所以需要使用await接收
await必须写在async函数中使用