0

METHOD 1

{
    var myform = getForm();
    var myVar = $sce.trustAsHtml(myForm);
}

METHOD 2

var getForm = function () {
    var form = "";
    //API CALL here using custom service
    .then(
    function (response) {
          form = //processing here
    },
    function (response) {
    }
    return form;
};

In below scenario I am calling getForm() method and need processed data from form variable. But it always return empty before processing.

How can I make this call sync so that I can getForm() return the processed data and returns to method 1

Kyle Krzeski
  • 6,183
  • 6
  • 41
  • 52
Gaurravs
  • 639
  • 1
  • 15
  • 30
  • `getForm` should return the promise from the custom service, and not do `then` in itself. do the `then` in method 1. – Claies Aug 18 '17 at 13:21
  • You can't. You need to understand and accept that an API call is asynchronous, and deal with it. The method can not return data. It can return a promise, or an observable of data, but not the data. – JB Nizet Aug 18 '17 at 13:21
  • Read [You're Missing the Point of Promises](https://blog.domenic.me/youre-missing-the-point-of-promises/). – georgeawg Aug 18 '17 at 13:31

1 Answers1

2

Deal with promise here:

var myform = getForm().then(
    (form) => {
       $sce.trustAsHtml($sce.valueOf(form))
    },
    (error) => {
       // getForm - fail
    });

METHOD 2 - return promise instead form value

var getForm = function () {
    return //API CALL here using custom service
};

Or even easier:

yourService.serviceMethod().then(
    (form) => {
       $sce.trustAsHtml(form)
    },
    (error) => {
       // getForm - fail
});
Gaurravs
  • 639
  • 1
  • 15
  • 30
Krzysztof Raciniewski
  • 4,735
  • 3
  • 21
  • 42