【问题标题】:why my data returning the state before get updated in async function nodejs typescript为什么我的数据在异步函数nodejs typescript中更新之前返回状态
【发布时间】:2021-11-26 00:35:08
【问题描述】:

我不知道为什么控制台日志中的变量 result 在此行中返回更新之前的状态

result[msisdn] = "customer exist"

它执行的代码本身,但是为什么在修改之前一直返回状态,我想我已经在我编写的所有异步代码上给出了 await 关键字

code.ts

async migrateCustomerImageUseCase(request: ListCustomerForMigration, response: Response): Promise<any>{
    const result = {} as any
    const lists = request as any

    await lists.forEach( async (element: any[]) => {
        const msisdn = element[0] as string
        const isCustomerExist = await this.ekycHandler.isCustomerExist(msisdn)

        if(isCustomerExist){
            result[msisdn] = "customer exist" as string
            this.logger.info(`${msisdn} = ${result[msisdn]}`);

            // tslint:disable-next-line:no-console
            // console.log(result[msisdn])

            // const customerImageData:CustomerImageData = {
            //     customerIdCardImage: element[2],
            //     customerImage:  element[3],
            //     msisdn: element[0] as string
            // };
            // const localFileName = await this.uploadBase64ImageToLocalUseCase(customerImageData, response)
            // const ossFileName = await this.uploadImageToOssUseCase(localFileName, response)

            // ossFileName["customerId"] = isCustomerExist.id
            // await this.ekycPortalRepo.createOrUpdateCustomerDetailCifFromMigrationData(ossFileName)

        } else {
            result[msisdn] = "customer not exist" as string
            this.logger.info(`${msisdn} = ${result[msisdn]}`);
        }

    })

    return result
}

code.ts 在另一个异步函数中被调用

const migrateResult = await this.ekycPortalUseCase.migrateCustomerImageUseCase(listCustomers, response)

【问题讨论】:

    标签: node.js typescript asynchronous


    【解决方案1】:

    我认为您的情况主要与此有关 - Using async/await with a forEach loop

    你确实不能使用 forEach。每个异步回调函数调用都会返回一个 Promise,但是您将它们扔掉而不是等待它们。只需使用 map 代替,您就可以等待通过 Promise.all 获得的一系列承诺

    你应该这样做:

    const promises = lists.map(() => {
      return (async () => {
        const msisdn = element[0] as string
        const isCustomerExist = await this.ekycHandler.isCustomerExist(msisdn)
    
        if(isCustomerExist){
            result[msisdn] = "customer exist" as string
            this.logger.info(`${msisdn} = ${result[msisdn]}`);
        } else {
            result[msisdn] = "customer not exist" as string
            this.logger.info(`${msisdn} = ${result[msisdn]}`);
        }
      })()
    })
    
    await Promise.all(promises)
    

    【讨论】:

      【解决方案2】:

      Typescript 在继续之前不会等待 forEach 完全完成,这就是为什么 return result 语句会在它被循环内部的结果填充之前被执行。

      一种解决方案可能是从使用 forEach 更改为基本的 for 循环,以完全避免此问题。

      【讨论】:

        猜你喜欢
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        • 2015-04-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-09
        • 1970-01-01
        相关资源
        最近更新 更多