Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

277
Visualizações
How to solve "Unhandled promise rejection" error?

I was trying to reuse the existing and working function in my azure timer trigger function. But I encountered an error below.

(node:66694) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch().

I already tried to wrap try-catch the setTimeout but still, the same error occurred.


here is my code:

export const request = async (
  reuqestOptions: Options,
  waitTime?: number
): Promise<Response> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // ... more code here
      
      const req = https.request(options, (res) => {
        // ... more code here

        res.on('end', async () => {
          // ... more code here

          resolve({
            body: result,
            statusCode: res.statusCode,
            headers: res.headers,
          })
        })
      })

      req.on('error', (e) => {
        console.log(e.message)
      })

      req.end()
    }, 3000 || 0)
  })
}

here is how I call request:

export const requestToken = async (
  usernmae: string,
  password: string
): Promise<any> => {
  try {
    const response = await request({
      method: 'POST',
      // ...more code here
    })

    if (response.statusCode !== 200) {
      throw new Error(JSON.stringify(response.body))
    }

    return response
  } catch (error) {
    throw new Error('request token is invalid')
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

So you have two places where you need to catch the error, or say, put a try block. First one would be the place where you make the http request. The other one would be the place where you actually call this function (which returns the promise).

wrapping the setTimeout in a try catch block will have no consequence as by the time the callback is fired, the try block would have ended.

For first case, you are registering an "error" callback, so thats all good. You just need to handle the second case (Promise).

export const request = async (
  reuqestOptions: Options,
  waitTime?: number
): Promise<Response> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // ... more code here
      
      const req = https.request(options, (res) => {
        // ... more code here

        res.on('end', async () => {
          // ... more code here

          resolve({
            body: result,
            statusCode: res.statusCode,
            headers: res.headers,
          })
        })
      })

      req.on('error', (e) => {
        console.log(e.message)
      })

      req.end()
    }, 3000 || 0)
  }).catch(err){
//...handle your error here
}
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda