Get the result inside an object is coming from ajax using getJson - javascript

Guys I try access and save the data is coming from ajax using getJson I have some like this
var conversation
conversation = $.getJSON("http://myapi&jsonp=?", function (response) {
return response;
});
console.log(conversation)
I get in my console this
I getting my data inside of responseJSON so I try do some like this
conversation.responseJSON.DATA
but this is give to me undefined what am I doing wrong ? can some one help me pleases

$.getJSON is an asynchronous call, that means that it doesn't get the results instantly, it make a call to the server and the results are available to the the callback function.
You need to put all the code that accesses the results returned from the server inside your callback function
function (response) {
// this is where your code goes.
}
In your code above the variable conversation is a promise, you don't get the results from the promise but with the callback function that runs when the promise resolves.
The usual way of access a promise is with a then call.
var conversationPromise = $.getJSON("http://myapi&jsonp=?");
conversationPromise.then(function(results) {
// Here is where your results are available.
});

Related

Javascript: .then() in promise is not executing?

I want a script file just for accessing a JSON from a url. I want to have a method to return the JSON object from the script into a var in a separate script file then modify it accordingly. Obviously since javascript is asynchronous it fails if I simply write it out. Therefore I must use a promise:
var promise1 = new Promise(function(resolve, reject) {
access(userSearchText); //send user input to get appropriate JSON object
});
promise1.then(function(value) {
var getData = returnData(); //method that returns JSON object from the other script
alert(getData); //print out the returned JSON object
console.log("we have finished");
});
But this is not printing out anything. The alert does not occur at all and nothing is being printed in the console. I am using jquery to access the url in the other script and I have a .done after accessing it in the script for retrieving the JSON as: access.js
var sendData;
(function() {
jqxhr = $.getJSON( url, {
})
.done(function( data ) {
sendData = data;
});
})();
function returnData(){
return sendData;
}
So there should not be any asynchronous issues in the script for accessing the URL because of .done. I really don't understand why this isn't working. I inspected my page and there are no errors to be seen anywhere. Can anyone help?
promise1 never gets resolved.
In your definition of promise1, you never call the resolve() function to resolve it. Thus, it's .then() never gets called.
Manually created promises are only resolved when you explicitly call resolve() in the executor function.
If access() is itself asynchronous, then we will need to more about that function to help you do this correct. Wrapping a promise around it does not do anything to help you. If access() itself returns a promise, you should just use that promise and not wrap one around it.
Probably access() should return a promise that is resolved when it's asynchronous operation is done and then you can do:
access().then(...).catch(...);
And, not wrap it with another promise.
The sendData and returnData() stuff just looks wrong. You'd have to explain and show more context to know what exactly the recommend.

How to access mysql record outside function in exprees.js

I am doing following code.
var data=[];
sequelize.query("SELECT `name`,`mobile` FROM `emp_table` LIMIT 0,50",function(result){
data['main']=result;
});
console.log(data['main']); // returns 'undefined'
I have used callback hell method. But I think this is not a right way.
Please help me.
since nodeJS in asynchronous console.log(data['main']); would be executed first, as the query is been processed(fetching data from db is async call).
you can try below code to get expected output.
var data=[];
sequelize.query("SELECT `name`,`mobile` FROM `emp_table` LIMIT
0,50",function(result){
data['main']=result;
console.log(data['main']);
});
I'm not sure what you mean with the callback hell method. But you're using a callback (the function supplied as a parameter) in the query() call. That function is only being called whenever query()'s body calls it. Making it behave asynchronous.
Problem now is, is the console.log is outside this 'async-loop' and ran sequentially. So data['main'] is actually undefined by the time console.log is called.
To fix it do this:
var data=[];
sequelize.query("SELECT `name`,`mobile` FROM `emp_table` LIMIT 0,50",function(result){
data['main']=result;
console.log(data['main']);
});
Move console.log into the callback.
You need to use promise when fetching data from db. You can print your data in then part of your code. Example:
Service that calls fetch data from db and returns a promise.
exports.getAllUsers = function() {
// this is the place where you will execute your query.
return models.user.findAll();
};
In the controller, the data is printed as.
userService.getAllUsers().then(function (result) {
if (result != null) {
res.status(200).json({
status: "success",
data: result
});
} else {
res.status(404).json({
status: "fail",
data: "No data found"
});
}
}

How do I create a variable with the result from $http in angular?

Im trying to get a json object from a http call with the following line.
var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
When I log it
console.log(u);
I dont get the json in return
Object { $$state: Object, success: $http/promise.success(), error: $http/promise.error()
How do i just make it return as a json string? Im using it in a factory if that matters. Thanks.
$http.get doesn't return the value which have been sent by API. It only returns the object of HttpPromise. To get the value you need to call the then function on the u
var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
u.then(function(response){
var yourVar = response.data;
console.log(yourVar);
});
For more see the Documentation
Assigning the http request to a variable doesnot mak the service call. You need to make the call as
var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
$scope.ResponeData = null;
u.then(function(response){
// Your response will be available here only
$scope.ResponeData = response;
});
You can find more details about the promises and web service call here.
When you perform an HTTP request, this request is not completed instantly, but rather it's completed asynchronously. So what happens is that when the request is made you get a sort of token (a Promise) that you can keep track of while the request is 'in the air'.
This promise is the object you log when you type:
var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
console.log(u);
To 'keep track' of this promise you can supply it with functions, somewhat similar to event handlers by using the then, error, success, and finally functions.
So here's what happens:
// Start the request and get a promise that an answer will eventually come.
var u = $http.get("http://localhost:8580/jettyjspconfiguration-example/sql?loc=locc");
// The request is handled asynchronously, so all we have now is the promise that
// at some time there will be a result.
console.log(u);
// Assign 'event handlers' to the promise
u.then(function(result) {
// This 'event handler' function is called when the async process completes
// successfully. You can now use the data as you please
doFancyStuffWithResultData(result.data);
}, function(error) {
// This 'event handler' function is called when the async process has an error
console.error('Ohnoz, things went wrong', error);
});
Note that I put 'event handler' in quotes because it helps to think of the functions as like-'event handlers', but there are some differences. Have a look at the documentation for the $q service for more information on what Promises are and how they work.

How to make $http.get return response instead of promise object?

var final;
final = $http.get('http://localhost:9000/therapist_data',config)
.success(function(response) {
console.log("I got the data I requested");
var resdata = response;
console.log(resdata);
return resdata;
});
console.log(final);
I am trying to return response data and store it into final variable instead I am getting the promise object.
How do I return actual data?
I'll try to develop Cyril answer based on your code :
var final;
final = $http.get('http://localhost:9000/therapist_data',config)
.success(function(response) {
console.log("I got the data I requested");
var resdata = response;
console.log(resdata);
return resdata;
});
console.log(final);
Here is the order of execution :
var final
$http.get('http://localhost:9000/therapist_data',config)
.success(); : this will trigger the request and register the function in success as a callback when server will have respond to your request
console.log(final); -> so still undefined. It does NOT WAIT for the response.
some times later ... your function in the success is called.
This is the very basis of callbacks and asynchonous processing, you don't know when it will be executed, or at least, it will often be executed after all the other code. In angularJS there is no way of doing a synchronous request. You must move you code in the success function.
As long as you are making a network call, your data will return back asynchronously, it is the nature of it, you can't fight it.
var wrongFinal; // <-- nope, final will never get into that scope
$http.get('http://localhost:9000/therapist_data',config)
.success(function(response) {
console.log("I got the data I requested");
var goodFinal = reponse; // <-- yes, here, the data lived
// do something with the data here
});
console.log(wrongFinal); // nop, wrong scope, no sense, data doesn't live here
Soooooo, the answer is a question:
What do you want to do with your data?
It depends on the destination. Are you going to make anoher network call? Do you want to update the view? Do you want to call a 3rd party library?
You need to understand and to embrace the nature of asynchronous in JavaScript.
$http.get will always return a promise.
If you'd like to get the promise value you should do it inside the success callback, like this:
var final;
$http.get('someUrl').success(function(response) {
final = response;
});
No need for resData, will only cause a promise chain, something you don't require in this case.

AngularJS promise not working

I have a promise that runs without a problem when it runs during application start, e.g.
myPromise
.success( function(data) { $scope.myvariable = data })
.error( function(msg, code) { console.log("msg: " + msg + "\nCode" + code) });
However if I try to run the promise dynamically, let's say when a button is clicked, (1) the promise executes successfully but none of my variables are updated.
running apply or digest only produces the following error: $digest already in progress
$scope.getContent = function() {
myPromise
.success( function(data) {
$scope.myVariable = data; //THIS WORKS
console.log(data); //THIS WORKS
})
}
//Running the below code afterwards still produces a null value
console.log($scope.myVariable);
This is what we called as async world.
When you are waiting for the callback of your promise the statement console.log($scope.myVariable); already executed but still you don't have any value in it.
In that case you can use $watch if you want to get it value outside.
$scope.$watch('myVariable',funciton(newVal){
console.log(newVal);
});
Little Detail:-
myPromise is invoked and waiting for the response in the meanwhile the statement console.log($scope.myVariable); after it executed which obviously doen't have any value for $scope.myVariable inside it (nobody gave it :-P). So when response came back it call the success or error method and initialize the value to your variable $scope.myVariable and print it.
Here your console.log($scope.myVariable); statement executes before success callback so here you need to do .then() chaining or apply watch on scope variable.
The reason your console.log, which comes after your promise logs null is because it is executing before your promise returns. Even though the function using the promise has run, the success part of the code has not fired yet. The code hits the promise, makes the calls, creates the promise object, and moves on. When the promise returns, it fills in the empty promise object with the returned data. This is happening after your
console.log($scope.myVariable);
A good way maybe to handle it is to store the returned value in a variable. Inside the success set the variable to the returned data, then use a function like
$scope.myVariable = undefined;
$scope.getContent = function() {
myPromise
.success( function(data) {
$scope.myVariable = data; //THIS WORKS
console.log(data); //THIS WORKS
})
}
function checker() {
if($scope.myVariable) {
console.log($scope.myVariable);
}
}
Then you can call that function as needed.
Depending on what you are doing and when your getContent function needs to run, you may want to use this with ui-router, and use resolve, which will run these functions before the page loads, thereby ensuring you have data to work with when the DOM loads.
AngularJS UI-Router: preload $http data before app loads
I think promise object makes call only once,when controller is initialized
you have to reinitialize controller,to get new updated values from server
A. Call sequence will be as follows when DOM ready:
1. $scope.getContent will get initialized.
2. then execution : console.log($scope.myVariable);
B. Async call:
1. If success then below statement will get executed.
$scope.myVariable = data; //THIS WORKS
Above point A and B are independent. Execution is asyc here.
Hope this will help you understand. Enjoy.
Maybe this can help :
// a service providing data with async call
app.service('myService', function(elasticQuery) {
this.getData = function (a,b,c) {
// don't forget the 2 return
return elasticQuery.search({
// make ajax call
}).then(function (response) {
return response
});
};
});
// in my controller
// scope.getData is lunch with ng-click in the view
$scope.getData = function(a,b,c){
myService.getData( a,b,c ).then(function (data) {
$scope.myVariable = data;
});
};

Categories