Have a nested asynchronous function in Typescript where i want to return a promise of an object.
async getContactByGUIDQuery(GUID: string): Promise<Contact> {
this.findContactByGUID(GUID).then(async (query) => {
this.querySalesforce(query).then(async (response) => {
return response.compositeResponse[0].body
}).catch((err) => {
return Promise.reject(err)
})
}).catch((err) => {
return Promise.reject(err)
})
}
Since you have the async
keyword there, I'm assuming you can use await
in your environment. And that makes things so much easier.
I believe this function does the exact same thing.
async getContactByGUIDQuery(GUID: string): Promise<Contact> {
const query = await this.findContactByGUID(GUID)
const response = await this.querySalesforce(query)
return response.compositeResponse[0].body
}
An async
function returns a promise, and if await
encounters a rejected promise in your function, it will also reject with that error.
So you don't need to catch and manually reject anything here at all. Just let async/await
work they were they are intended to.