asynchronousfunction – 等待不等待承诺

我试图学习asynchronous等待。 在这个代码中 –

const myFun = () => { let state = false; setTimeout(() => {state = true}, 2000); return new Promise((resolve, reject) => { setTimeout(() => { if(state) { resolve('State is true'); } else { reject('State is false'); } }, 3000); }); } const getResult = async () => { return await myFun(); } console.log(getResult()); 

为什么我得到的输出为 –

 Promise { <pending> } 

而不是一些价值? getResult()函数是否应该等待myFun()函数解决它的promise值?

如果你正在使用async / await,你的所有调用都必须使用Promises或者async / await。 你不能神奇地从同步调用中获得asynchronous结果。

您的最终通话需要是:

 getResult().then(response => console.log(response)); 

或者类似的东西:

 (async () => console.log(await getResult()))()