异步等待未按预期工作 [英] Async Await does not work as expected

查看:80
本文介绍了异步等待未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我们将短字符串存储为键.

Currently we are storing short strings as keys.

这些键对应于作为标签的长值.

These keys correspond to long values which are labels.

我正在尝试更新密钥的相应长值.

I am trying to update the corresponding long value for the key.

但是console.log(record)总是首先执行,然后执行内部log语句,这是不希望的.它总是将未修改的记录发送到getRadioValues函数调用者.

But the console.log(record) always executes first and then the inner log statement executes which is not is desired. It always sends the unmodified record to the getRadioValues function caller.

我想在相应的密钥更新后返回记录.

I want to return the record after the corresponding key is updated.

export const getRadioValues = (record: IRecordInput) => {
    const singleSelectKeys = ['Race', 'DeathWas', 'MannerOfDeath'];
    singleSelectKeys.forEach(async key => {
        if (record[key]) {
            const dropDownOption = await DropDownOptions.find({ where: { id: record[key] }}) as IPDFSelect;
            record[key] = dropDownOption.dataValues.Text;
            console.log(record[key]);
        }
    });
    console.log(record);
    return record;
};

推荐答案

您的forEach使用的是异步函数,这意味着循环可能要在其创建的任何承诺完成之前完成.要解决此问题,您需要获取承诺的结果并等待它们.但是,这意味着封装函数本身必须是异步的,对于您的实际用例而言,这可能是可接受的,也可能是不可接受的.

Your forEach is using an async function which means that the loop probably finishes before any of the promises it created do. To fix this, you need to get the result of your promises and wait on them. However, this means the enclosing function must itself be async, which may or may not be acceptable for your actual use case.

export const getRadioValues = async (record: IRecordInput) => {
    const singleSelectKeys = ['Race', 'DeathWas', 'MannerOfDeath'];
    await Promise.all(singleSelectKeys.map(async key => {
        if (record[key]) {
            const dropDownOption = await DropDownOptions.find({ where: { id: record[key] }}) as IPDFSelect;
            record[key] = dropDownOption.dataValues.Text;
            console.log(record[key]);
        }
    }));
    console.log(record);
    return record;
};

这篇关于异步等待未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆