【问题标题】:react JS, async await access promise valuereact JS,异步等待访问承诺值
【发布时间】:2021-10-14 05:11:32
【问题描述】:

我有以下异步功能,

async function getScriptText(structure, dicto) {
        try {
            const rand = Math.floor(Math.random() * (max - min + 1)) + min;
                const response = await {text:dicto[rand].text, title:dicto[rand].title}
                return response
        } catch (error) {
            console.log("errore:",error)
        }

    }

然后我用它

            const scriptModel =  [
{script: getScriptText(props.sessionItem["induction"], iDicto)} ]

但是当记录scriptModel时,我看到promise不是值,请问如何使用返回值?

【问题讨论】:

  • 这就是 javascript 的 async 函数的工作原理。一旦你将它们声明为async,任何从函数返回的值都将被包装在一个promise中。
  • 您确定要它成为async 函数吗?你为什么await-ing 一个简单的对象?
  • 感谢@RoboRobok,它正在查找一个很长的 JSON 字典来组合对象
  • @manuelBetancurt 您是否在使用某种异步执行的库?因为使用内置 JSON 解析器这样做没有意义——它不是异步的。
  • @RoboRobok,谢谢,只是从 JSON 文件中组合对象,没有使用任何库,但需要等到完成才能渲染屏幕值,否则有时会崩溃,因为从 JSON 文件构造对象有时需要更长的时间

标签: javascript reactjs async-await


【解决方案1】:

不确定在您的情况下使用async 是否有意义,但为了从promise 中读取值,您需要使用.then()await

.then():

let scriptModel;

getScriptText(
    props.sessionItem["induction"],
    iDicto
).then(result => scriptModel = {script: result});

await:

let scriptModel;

(async () => {
    scriptModel = {
        script: await getScriptText(
            props.sessionItem["induction"],
            iDicto
        )
    };
})();

【讨论】:

  • sn-ps 不实用,未链接的承诺很可能会导致竞争条件。这就需要将scriptModel用于异步控制流的地方适配
猜你喜欢
  • 2023-04-06
  • 1970-01-01
  • 2017-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-07
  • 2021-05-25
  • 2018-02-03
相关资源
最近更新 更多