Javascript - async await 不等到功能完成?

Javascript - async await not wait until function is done?

我正在学习 javascript 使用 async 和 await 并自己尝试了一些示例,但似乎在从另一个函数 (func2) 调用异步函数 (func1) 时,func2 不会等待 func1完成它的过程并跳过并继续执行...我的代码有问题还是我也应该将 func2 转换为异步并使用 await 调用 func1?如果是这样,是否意味着所有涉及 async-await 方法的函数也需要变为异步? 这是我的原始代码

// func1
const func1 = async() => {
   try {
     await putCallToServer(...);
     return 1;     // it returns as a promise
   } catch(ex) {
     return 2;
   }
}

// func2
const func2 = () => {
   let result = 0;
   result = func1(); // should I turn it into await func1()??
   console.log(result);  // log contains '0' instead of '1' or '2'
   return result;    // return as Promise but value inside is 0
}

如果我有一个调用 func2 的 func3,我是否也应该将 func3 转换为 async-await?

如评论中所述,两个函数都必须异步才能使用 await。这可以在下面的代码片段中看到。 (因为我不想在示例中调用实际服务器,所以我投入了 putCallToServer()。这将返回 2.

的结果

我还将 result 更改为一个 let 变量,因为您试图 mut 一个不允许的 const。

async function putCallToServer() {
 throw "too lazy to make a real error"
}
// func1
const func1 = async() => {
   try {
     await putCallToServer();
     return 1;     // it returns as a promise
   } catch(ex) {
     return 2;
   }
}

// func2
const func2 = async() => {
   let result = 0;
   result = await func1(); // should I turn it into await func1()??
   console.log(result);  // log contains '0' instead of '1' or '2'
   return result;    // return as Promise but value inside is 0
}
func2()