Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert promise in JSON object

I have a problem converting the promise returned by the service to the controller. What I want is to create an array of JSON objects from the data contained in promise. Here is what I receive in the controller: Data received at controller

Here is the line that is used for printing that data:

console.log("controller unmatched: ", unmatched.getData(sFilter));

Here "unmatched" is the service, and getData() is its function.

Thanks!

like image 674
VitezKoja Avatar asked Jun 02 '17 14:06

VitezKoja


People also ask

Is json () a promise?

json() The json() method of the Response interface takes a Response stream and reads it to completion. It returns a promise which resolves with the result of parsing the body text as JSON .

Why does json return promise?

The value is returned because promise has been resolved passing the value in response.


1 Answers

A Promise represents a value that will be available some time in the future, or never. This means its eventual value can't be returned by your unmatched.getData() function.

What you need to do is to make unmatched.getData() return the actual promise and then you take action when that promise resolves:

unmatched.getData(sFilter).then(function(result) {
  console.log("controller unmatched: ", result);
});
like image 99
Lennholm Avatar answered Oct 04 '22 08:10

Lennholm