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
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?
>Solution :
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. In order to await it your map function needs to be an async function, which means you’re 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)
}
