-1

When I call loadhtml method from show .I am always get a pending promise. How do I get value without a call back. Please find the code snip below.

   async loadhtml(url: string) {
            var data =$.get(url).then(response=>{
                console.log("response=>",response)
                return response
            });
            return await data
        }

 show() {
      var data = this.loadhtml(require("../../template/template1.tpl"));
       console.log("html content=> ",data);
} 
Vipin
  • 938
  • 5
  • 18
  • 36
  • You need to resolve the promise; either show also needs to be async or you need to use then. – jonrsharpe Oct 13 '18 at 08:06
  • Can you please provide me an example. I am very new to this – Vipin Oct 13 '18 at 08:09
  • You already have examples of both of these things *in the code you've posted*. – jonrsharpe Oct 13 '18 at 08:09
  • Possible duplicate of [Returning an awaited value returns a Promise? (es7 async/await)](https://stackoverflow.com/questions/39812505/returning-an-awaited-value-returns-a-promise-es7-async-await) – JJJ Oct 13 '18 at 08:22
  • But question is i don't want to again write a then . If you see here in this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await#Examples. If the value is not a promise await return a value . In here response is a html. What might be the reason i am not getting html? – Vipin Oct 13 '18 at 08:28
  • Yes, **`await`** returns a value, but the **`async`** function always returns a promise. You're logging what the async function returns, not the awaited value. – JJJ Oct 13 '18 at 08:36
  • I got it. Thanks. My question was this. – Vipin Oct 13 '18 at 08:40

1 Answers1

-1

You can wrap it inside a promise and return so that you can use await in the caller function to wait for it.

async loadhtml(url: string) {
  return new Promise((resolve, reject) => {
    $.get(url).then( response => {
      console.log("response=>",response)
      resolve(response)
    });
  });
}

async show() {
  var data = await this.loadhtml(require("../../template/template1.tpl"));
  console.log("html content=> ",data);
} 
JJJ
  • 32,902
  • 20
  • 89
  • 102
Akash Dathan
  • 4,348
  • 2
  • 24
  • 45
  • There's no point in wrapping an async function in a promise because it already returns a promise. *And* `$.get` already returns a promise so you have a promise wrapped in a promise wrapped in a promise. – JJJ Oct 13 '18 at 11:23