Search code examples
typescriptasynchronousnestedarrow-functions

Best way to return response within nested arrow functions in Typescript


Have a nested asynchronous function in Typescript where i want to return a promise of an object.

  1. Do I need both functions to include a "catch" where i return a promise.reject() or do i just need one Catch?
  2. This format still gives me an error of "A function whose declared type is neither 'void' nor 'any' must return a value" due to there not being a return statement outside of the functions. Even using a try catch around the whole thing gives me the same error.
    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)
        }) 
    }

Solution

  • 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.