Home > other >  why my data returning the state before get updated in async function nodejs typescript
why my data returning the state before get updated in async function nodejs typescript

Time:11-25

i dont know why variable result in console log is returning the state before get updated in this line

result[msisdn] = "customer exist"

the code itself it executed but why keep returning the state before get modified, i think i already give await keyword on all async code that i write

log view

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
}

and the code.ts is called in another async function with this line

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

CodePudding user response:

I think your case is mostly connected with this - Using async/await with a forEach loop

You cannot use forEach indeed. Each of the async callback function calls does return a promise, but you're throwing them away instead of awaiting them. Just use map instead, and you can await the array of promises that you'll get with Promise.all

You should do something like that:

   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)

CodePudding user response:

Typescript doesn't wait for a forEach to be fully completed before moving on, that's why the return result statement gets executed before it is filled with the results from inside the loop.

One solution might be to change from using forEach to a basic for loop to avoid this issue entirely.

  • Related