JAVASCRIPT-Async不等待,直到函数完成?函数、JAVASCRIPT、Async

2023-09-03 09:12:23 作者:半粒糖、甜到伤

我在学习使用Async和AWait的Java脚本,并亲自尝试了一些示例,但当从另一个函数(Func2)调用Async函数(Func1)时,Func2似乎没有等待Func1完成其过程,它跳过并继续执行...是不是我的代码有问题,或者我是否应该也将Func2转换为Async并使用AWait调用Func1?如果是这样的话,这是否意味着所有涉及异步等待方法的函数也需要变为异步? 以下是我的原始代码

// 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
}

如果我有一个函数3,它将调用函数2,我是否应该将函数3也转换为异步等待?

推荐答案

如注释中所述,这两个函数必须同步才能使用AWait。这可以在下面的代码片段中看到。(因为我不希望在示例中调用实际的服务器,所以我抛出了putCallToServer()。这将返回%2的结果。

JavaScript可视化 Promise和Async Await

我还将Result更改为let变量,因为您试图静音不允许的常量。

数据-lang="js"数据-隐藏="假"数据-控制台="真"数据-巴贝尔="假">
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()