How to save the response from an asynchronous call to variable [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a API call and I expected to write response to friends variable.
getFriends = function() {
return VK.Api.call('friends.get', {}, function(response) {
if (response.response)
response.response;
});
};
var friends = getFriends();
console.log(friends) // undefined;
In my previous question one guy told me that I can fix it with callback function and close my question. I implement a callback but again I can't get a response.
var getFriends = function(callbackFn) {
return VK.Api.call('friends.get', {}, function(response) {
if (response.response) {
callbackFn(response.response);
}
});
};
var friends = getFriends(function(list) { return list; });
How I can write response.response to variable for a lot of next manipulations?

It's actually much simpler
var friends = null;
VK.Api.call('friends.get', {}, function(response) {
if (response.response) {
friends = response.response;
console.log(friends);
}
}

Related

I don't know why same value is not correct [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 7 years ago.
function checkEmailValid(email,result)
{
if(email.val()==""){
result.text("이메일을 입력하십시요.");
return false;
}
else{
var re_mail = /^([\w\.-]+)#([a-z\d\.-]+)\.([a-z\.]{2,6})$/;
if(re_mail.test(email.val())){
var res = false;
$.ajax({
type:"GET",
url: "http://127.0.0.1:3000/auth/checkemail/"+email.val(),
timeout: 2000,
beforeSend: function(){
result.text("이메일 확인 중...");
},
complete: function(jqXHR){
if(jqXHR.status==202){
res = true;
}else{
result.text("이미 등록된 이메일입니다.");
res = false;
}
},
success:function(data,textStatus,jqXHR){
},
fail: function(){
}
});
alert("step2 : " + res); ////////Here is Step2!!!
alert("step3 : " + res); ///////Here is Step3!!!
return res;
}else{
result.text("이메일 형식이 올바르지 않습니다.");
return false;
}
}
}
Above function is for Email Validation:
If the email is valid the function will return true, but oddly enough res of step2 is false and res of step3 is true. What is happening?
Step 2 value:
Step 3 value:
i will not suggest you for setting "async" to false
because it is a bad practice but you can use callback function to perform your task on true condition
i will explain
first of all add another parameter in your function like
function checkEmailValid(email,result,SuccessCallback)
and create a function with which will perform your task when ajax return true
like
function EmailIdIsUnique()
{
//perform your code here
}
and call this callback funtion in ajax
like
complete: function(jqXHR){
if(jqXHR.status==202){
//run your code here
if ($.isFunction(SuccessCallback))
{
result = successcallback.call(this);
}
}else{
result.text("이미 등록된 이메일입니다.");
res = false;
}
},

Get result from JavaScript Promise (.then function) when doing API call? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I'm a total beginner at Javascript, and I'm trying to get some data from an API, and have code that looks roughly like this:
function getData(uid) {
app.login({ email: userEmail, password: userPassword}).then(function(response){
var user = response.user;
var result = user.read(uid).then(function(){
return "foobar";
});
return result;
});
}
function doStuff(uid) {
var result = getData(uid);
// do stuff on result
console.log(result); //returns promise
}
So I want to access the result var result = getData(user, uid); which only returns a Promise object. What's the best way to get access to the "foobar" result?
You can't return a result from a deferred request. What you should do is use a callback function like this...
function getData(uid, callback) {
app.login({ email: userEmail, password: userPassword}).then(function(response){
var user = response.user;
var result = user.read(uid).then(function(){
return "foobar";
});
callback(result);
});
}
function doStuff(uid) {
getData(uid, function(result) {
// do stuff on result
console.log(result); //returns promise
});
}

Ajax Jquery: how return result? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
In script-a.js I have this function:
function callGetAjax(url,callback) {
$.get(url, {}, function(result) {
// this will call the callback and pass the result
callback(result);
});
}
In script-b.js I call it:
var url = '/feed/location';
callGetAjax(url,function(result)
{
//console.log(result); <= of course this logs right
data = result;
return data;
});
console.log(result); // <= ReferenceError: result is not defined
console.log(data); // <= ReferenceError: data is not defined
I don't want make async:false but I need to "export" data to elaborate it. Thank you.
Ajax is an async tool so you can use data only inside it. So, if you need to alter the dom with data you should do it directly:
var url = '/feed/location';
callGetAjax(url,function(result)
{
//console.log(result); <= of course this logs right
data = result;
$('#some_dome_item').html(data);
});

variable not being returned (unidentified) - AngularJS [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
In my controller I am calling the function
function initialiseQuizContent(quizIdArray){
alert(getQuizService.getQuizContent(quizIdArray));
}
which calls the a method in the following service
app.service('getQuizService', function($http) {
var quizArray;
this.setQuizArray = function(quiz){
quizArray = quiz;
};
this.getQuizArray = function(){
return quizArray;
};
this.getQuizContent = function(quizArray){
var $promise=$http.get("http://localhost/PHP/getQuizContent.php", {'quizArray': quizArray}); //send data to addQuiz.php
var theReturn;
$promise.then(function(msg){
//alert(msg.data);
theReturn = msg.data;
});
return theReturn;
};
});
However the result I get for the alert is 'undefined'. I know that the call to the PHP file works fine as if I put 'alert(msg.data)' within the promise, as commented out above, then the correct array is returned. I am new to this so excuse any silly questions but it seems as if the value that is being returned for the 'getQuizContent()' method is done before the PHP file is executed and the msg.data is received? Resulting in the undefined variable 'theResult'.
I would appreciate any help. Thanks
Working with $http service means working with AJAX, the response is asynchronous, that why you got undefined, I would suggest changing your service and doing something like this:
app.service('getQuizService', function($http) {
var quizArray;
this.setQuizArray = function(quiz){
quizArray = quiz;
};
this.getQuizArray = function(){
return quizArray;
};
this.getQuizContent = function(quizArray){
var promise=$http.post("http://localhost/PHP/getQuizContent.php",
{'quizArray': quizArray}).then(function (response) {
console.log(response);
return response.data;
});
return promise;
};});
then in controller do something like this:
function initialiseQuizContent(quizIdArray){
getQuizService.getQuizContent(quizIdArray).then(function(data){
alert(data);
});
}

undefined variable after ajax request [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm using jQuery. I have a function that fetches data from a remote server called "get_cats". I call it to fill an array with the values returned. When AJAX is completed I want to return the values.
But It doesn't work, the value returned is undefined. This is pretty basic but I can't see where It fails. Does anyone has a clue ?
$(function () {
var url = "http://someurl.com/service/";
var cats = [];
cats = get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
return categories;
});
}
$(document).ajaxStop(function () {
console.log(cats); // fails and returns undefined :'(
});
});
Oh no AJAX is asynchronous, you cannot return anything from it. You should consume the results of an AJAX request only inside the success callback:
$(function () {
var url = "http://someurl.com/service/";
get_cats(url);
function get_cats(url) {
var categories = [];
$.getJSON(url + "cats", function (data) {
$.each(data, function (i) {
categories.push(data[i].name);
});
// Only here you can consume the results of the AJAX request
// Do not attempt to return them, it doesn't make any sense
console.log(categories);
});
}
});
You can try:
$.ajaxSetup({async:false});
before AJAX call.
But it will stop browser while respone will be returned.

Categories

Resources