Home > other >  How to input Promise string value into an object
How to input Promise string value into an object

Time:02-08

In the code below

const getOptionName = async(id): Promise<void> => {
  const data = await dealStore.findById(id)
  console.log('data.optionName', data.optionName)
  console.log('typeof(data.optionName)', typeof(data.optionName))

  return data.optionName
}

const openRemoveDialog = (): void => {
  const checkedItems = grid1.current.getCustomCheckedList().map(item => {
    return {
      optionName: getOptionName(item.id),
      channelName: item?.channelName,
      name: item?.name,
      id: item.id,
    }
  })
  console.log('checkedItems', checkedItems)
}

My console.log('data.optionName', data.optionName) outputs

data.optionName 딜 옵션명 테스트

My console.log('typeof(data.optionName)', typeof (data.optionName)) outputs

typeof(data.optionName) string

My console.log('checkedItems', checkedItems) gives the following output

enter image description here

I am confused why my optionName value is a Promise instead of a string when console.log('typeof(data.optionName)', typeof (data.optionName)) shows me that data.optionName is a string

I want my optionName value to be a string and not a Promise. How do I input the PromiseResult string value into my optionName?

CodePudding user response:

If possible you should change your Promise to ask for findByIds(ids: number[]) to get all data matching a set of IDs rather than one singular ID - this will reduce the number of network calls and remove the anti-pattern of making Promises within your map closure.

But if you want to not retrieve a Promise for optionName you'll also have to await the result of that promise as well.

return await data.optionName;

CodePudding user response:

getOptionName is an async function, so it will return a promise. To get the value out of that promise you'll need to await it. That in turn means you'll be creating an array of promises. You can then use Promise.all to combine the array of promises, and await it to get your finished array of objects.

const openRemoveDialog = async (): void => {
  const promises = grid1.current.getCustomCheckedList().map(async (item) => {
    return {
      optionName: await getOptionName(item.id),
      channelName: item?.channelName,
      name: item?.name,
      id: item.id,
    }
  }
  const checkedItems = await Promise.all(promises);
  console.log('checkedItems', checkedItems)
}
  •  Tags:  
  • Related