0

Whenever I try to run this function:

async function jget(url){
    await $.get(url, html => {
        return html
    })
}

I get an error like this:

(node:13924) UnhandledPromiseRejectionWarning: #<Object>

How can I fix this?

shie1
  • 3
  • 2

1 Answers1

1

You should put the "$.get(url, handlerFunction)" into a promise as await expects a Promise to return, so instead of your code you can write your code like below.

async function jget(url){
    // Note: Below variable will hold the value of the resolved promise
    let response = await fetchingData(url);
}

function fetchingData(url) {
    return new Promise((resolve, reject) => {
      $.get(url, html => {
        resolve(html)
    })
})
}
  • I had to add "return response" to jget, but it's working perfectly! Thank you so much! – shie1 Aug 12 '20 at 22:15
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it), `jQuery.get` already returns a promise! Your approach is ignoring errors. – Bergi Aug 12 '20 at 22:26