本文介绍了异步功能 - 等待不等待承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试学习async-await。在此代码中 -
I'm trying to learn async-await. In this code -
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());为什么我输出为 -
why am I getting output as -
Promise { <pending> }而不是某些价值?不应该 getResult()函数等待 myFun()函数解析它的promise值?
Instead of some value? Shouldn't the getResult() function wait for myFun() function resolve it's promise value?
推荐答案如果您正在使用async / await,则所有调用都必须使用Promises或async / await。你不能只是神奇地从同步电话中获得异步结果。
If you're using async/await, all your calls have to use Promises or async/await. You can't just magically get an async result from a sync call.
您的最终通话需要是:
getResult().then(response => console.log(response));或类似:
(async () => console.log(await getResult()))()更多推荐
异步功能
发布评论