异步功能

编程入门 行业动态 更新时间:2024-10-26 20:35:10
本文介绍了异步功能 - 等待不等待承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试学习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()))()

更多推荐

异步功能

本文发布于:2023-11-23 10:21:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1621096.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:功能

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!