【级联下拉选项请求异步问题解决】

文章讨论了在处理级联下拉列表值的异步请求时,如何正确使用async/await、for循环和Promise.all。作者指出直接用state.push和setState保存值是错误的,应使用forof循环或Promise.all确保所有请求完成后更新状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

关于这种级联的下拉列表值请求,通常会有一个异步的问题,可以这样:直接用state的数据push进去,再调用setState(val => […val])保存一下自己的值,这样就可以了。

1、这种方法是错误的,因为map/forEach中async和await不会生效

  /** 得到下拉列表值 */
  const getDictList = async () => {
    service.getAAAAA().then((res: any) => {
      if (res && res.length) {
        let arr: any = [];
        res.map(async (item: any) => {
          const val = item.value.toUpperCase();
          await getDict(`TYPE_${val}`, false).then(
            (result: any) => {
            // ---------------------------------
              state.push(...result);
              setState((val: any) => [...val]);
            },
          );
        });
      }
    });
  };

2、可以用for循环,Promise.all,for of循环,在这些循环里面,才会等待完成async和await的执行,才能得到每次请求到的数据

1、使用for of循环

  /** 得到下拉列表值 */
  const getDictList = async () => {
    service.getAAAAAA().then(async (res: any) => {
      if (res && res.length) {
        for (const item of res) {
          const val = item.value.toUpperCase();
          const result = await getDict(`TYPE_${val}`, false);
          state.push(...result);
        }
        setState((val: any) => [...val]);
      }
    });
  };

2、使用for循环

  /** 得到下拉列表值 */
  const getDictList = async () => {
    service.getAAAA().then(async (res: any) => {
      if (res && res.length) {
        let arr: any = [];
        for (let i = 0; i < res.length; i++) {
          const val = res[i].value.toUpperCase();
          const result = await getDict(`TYPE_${val}`, false);
          arr.push(...result);
        }
        setState(arr);
      }
    });
  };

3、使用Promise.all方法

  const getDictList = async () => {
    service.getAAAAAA().then((res: any) => {
      if (res && res.length) {
        let promises: Promise<any>[] = [];
        res.forEach((item: any) => {
          const val = item.value.toUpperCase();
          const promise = getDict(`TYPE_${val}`, false);
          promises.push(promise);
        });

        Promise.all(promises).then((results) => {
          results.forEach((result: any) => {
            state.push(...result);
          });
          setState([...allExpressProTypeList]);
        });
      }
    });
  };
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

呐呐呐呐。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值