I've been trying for a while to get the data from this call, but it always returns "undefined"
httpCall = function(sTformName) {
let sURL = "https://urlthisone/api/",
response;
$http.get(sURL)
.success(function(data) {
response = data;
});
}
Any ideas on what I'm doing wrong?
Thanks in advance.
You can return and resolve the promise...
httpCall = function(sTformName) {
let sURL = 'https://urlthisone/api/',
return $http.get(sURL);
}
httpCall('myForm').then(response => {
console.log(response.data);
});
$http.get is an asynchronous call and must be handled accordingly, in this case, by resolving the returned Promise
You're making an async call, and it will not return a value. It calls success and inside success you need to use a callback method in order to get the value you want, and work with it.
function doSomethingWithTheData(data) {
// process the data here.
}
httpCall = function(sTformName, callback) {
let sURL = "https://urlthisone/api/",
response;
$http.get(sURL)
.success(function(data) {
callback(data); // here's where we call the callback
});
}
// call it with the callback
httpCall(fornName, doSomethingWithTheData);
Please, see documentation - https://docs.angularjs.org/api/ng/service/$http#get
According to it, if you use angular.js 1.4.3+, $http.get(sURL) returns promise. So you need $http.get(sURL).then(...)
Also, see $http.get(...).success is not a function might will help
Related
I've got this Node.js snippet.
var requestify = require('requestify');
// [...]
function remoterequest(url, data) {
requestify.post(url, data).then(function(response) {
var res = response.getBody();
// TODO use res to send back to the client the number of expected outputs
});
return true;
}
I need to return res content instead of true, back to the caller.
How can I do that?
In this case, the requestify's method is asyncronous, therefore, the returned value is not possible to be retrieved (since it's not generated yet).
How can I solve it? How can I send a synchronous HTTP POST request (even without requestify)?
you need to return a promise and use it in the then method of the promised returned by remoteRequest :
var requestify = require('requestify');
// [...]
function remoterequest(url, data) {
return requestify
.post(url, data)
.then((response) => response.getBody());
}
//....
remoteRequest('/foo', {bar: 'baz'}).then(res => {
//Do something with res...
});
Note that it still won't be a synchronous POST though, but you will be able to use response.getBody() when available, If this is what you wanted
You can refer to this discussion about how to use content returned from a promise How do I return the response from an asynchronous call?
As mentionned by #Logar, you can't use directly the content returned in your promise. You must call your method returning a promise first, and use .then to make the returned content available.
Example:
var requestify = require('requestify');
// [...]
// This function returns a promise, so you have to call it followed by `.then` to be able to use its returned content
function remoterequest(url, data) {
requestify
.post(url, data)
.then((response) => {
return response.getBody();
});
}
//....
//... Some other code here
//....
// Make a call to your function returning the promise
remoterequest('your-url-here', {data-to-pass-as-param})
.then((res) => { // Calling `.then` here to access the returned content from `remoterequest` function
// Now you can use `res` content here
});
I'm using Meteor and React, and I'm trying return data from a third party javascript function
The function takes a callback and returns a value. The function takes a few seconds to resolve
At the moment the callback returns an undefined value but after a few seconds a console log will display the correct data
My current code is as follows
// ON THE CLIENT
// callback function that returns a deviceId
const callback = function( data ) {
// this callback fires with the correct data after a couple of seconds
console.log("Callback ", data);
return data;
};
// async function that calls third party function with callback
async function getDeviceId() {
const res = await captureDeviceId(callback);
return await res;
}
let response = getDeviceId().then( function(value) {
return value;
});
console.log("res", response);
The response returns a promise but does not resolve
Return {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}
How can I wait for the functions response before returning the value?
I've tried Meteor wrapAsync, async-await and Promises without success.
Any help would be appreciated
Cheers,
getDeviceId returns here a promise (even if you do a return inside the .then callback). If you want to ge the value, do it like below:
var response;
getDeviceId().then( function(value) {
response = value;
});
I have created a function expression and assigned it to scope, the idea being that the function will initiate an $http request, get a property and then return it.
$scope.getRequestDigest = function () {
var url = urlParams['SPAppWebUrl'] + '/_api/contextinfo';
$http.post(url)
.success(function (res) {
return res;
});
}
However when I call $scope.getRequestDigest() it simply returns undefined, presumably because the ajax call hasn't completed yet. Is there any way to delay the return until the $http request is complete? I've tried using the .success() promise but that doesn't seem to work.
$http.post returns a promise (see $q). In order to use the result, bind res to $scope.res:
controller:
$scope.getRequestDigest = function () {
var url = urlParams['SPAppWebUrl'] + '/_api/contextinfo';
$http.post(url)
.success(function (res) {
$scope.res = res;
});
}
Then, you can use $scope.res (or res in the template) anywhere you'd like.
After the promise chain is resolved (after success), Angular will run a digest cycle and rebind everything on $scope.
Try
$scope.getRequestDigest = function () {
var url = urlParams['SPAppWebUrl'] + '/_api/contextinfo';
return $http.post(url);
}
var digestPromise = $scope.getRequestDigest();
digestPromise.then(function(response){
console.log(response.data);
});
This way you are actually returning a promise, which AngularJS implements through the $q service.
If you were to output (console.log(digestPromise)) digestPromise, you will see that you can all sorts of functions on it, like success or complete, for example.
You could use chain promise using .then
$scope.getRequestDigest = function () {
var url = urlParams['SPAppWebUrl'] + '/_api/contextinfo';
return $http.post(url) //this will return a promise
.then(function (res) {
return res.data; //on success this will return a data to caller function
});
}
Then the caller function will have call the function and get the data like this
$scope.getRequestDigest().then(function(data){
console.log(data)
//here you can get data returned from `getRequestDigest` method
})
Is there a way to store data to a variable?
I tried:
$scope.another =
function(){
var new_data;
userService.getInfo().success(function(data){
new_data = data;
});
return new_data;
};
var data = $scope.another();
but it returns 'undefined' in the console log. Thank you
EDIT
I now get an empty array for new_data .
var new_data = [];
$scope.another =
function(callback){
userService.getInfo().success(function(data){
paymentService.getCashierParams({ "cardNumber": data.cardNumber}).success(function(data){
gameService.getAllgames({ "PID":data.GetCashierParameters.PID, "limit": 6, "skinID": 1}).success(function(data) {
callback(data.data.GetFlashGamesResult.Data.FlashGame);
});
});
});
};
$scope.another(function(result){
new_data = result;
});
console.log(new_data);
You need to think about this problem differently. Your getInfo method returns a promise. A promise's success callback is never immediately called. It may be called sometime in the future, but in the meantime your code will continue executing and the return value of $scope.another will be undefined.
Instead, place whatever logic you wish to execute within the success callback.
userService.getInfo().success(function (data) {
// Do stuff with data.
});
If you are not used to working with asynchronous data, this may seem weird. But it is much better than the alternative, which is hanging the page for potentially many seconds while a network request, database read, etc, completes.
If you are worried about indentation, you can create separate function(s) to handle the data.
function processData(data) {
// Process stuff...
return data;
}
function handleData(data) {
data = processData(data);
console.log(data);
}
userService.getInfo().success(handleData);
This is due to the asynchronous function that you called. Try to use callback instead. Something like this:
$scope.another =
function(fn){
userService.getInfo().success(function(data){
fn(data);
});
};
var data = $scope.another(function(doSomething) {
alert(doSomething);
return doSomething;
};
What I'm trying to do is the following in JS:
function getSuccessForTest(testName,version,fromRev,toRev,res) {
var params = {
"methodToRun":"getSuccessForTest",
"version":version,
"startRev":fromRev,
"endRev":toRev,
"testName":testName
};
$.post("Stats.php", params,function(data){
return parseInt(data.toString(),10);
}, "json");
}
getSuccessForTest(data[i],version,fromRev,toRev,res);
What am I doing wrong ? whenever I make the call to getSuccessForTest, I get the POST result in Stats.php but the value isn't returned to the calling function.
Thanks in advance !
It's not working because the return is in the callback function given to $.post as a parameter. Since you're dealing with an ajax request which is asynchronous you need to use a callback for getSuccessForTest as well. Try this:
function getSuccessForTest(testName,version,fromRev,toRev,res, callback) {
var params = {
"methodToRun":"getSuccessForTest",
"version":version,
"startRev":fromRev,
"endRev":toRev,
"testName":testName
};
$.post("Stats.php", params,function(data){
callback(parseInt(data.toString(),10));
//return parseInt(data.toString(),10);
}, "json");
}
getSuccessForTest(data[i],version,fromRev,toRev,res, function (data) {
alert(data); // This would be the value you wanted to return
});
That's beacuse value is returned to the anonymous function (function(data){...). Use callbacks. Try this:
function getSuccessForTest(testName,version,fromRev,toRev,res, callback) {
var params = {
"methodToRun":"getSuccessForTest",
"version":version,
"startRev":fromRev,
"endRev":toRev,
"testName":testName
};
$.post("Stats.php", params,function(data){
callback(parseInt(data.toString(),10));
}, "json");
}
getSuccessForTest(data[i],version,fromRev,toRev,res, function(res) {
alert(res)
} );
use echo when you are return from stats.php. if this is not solving your issue then I would like to know what is the return method you are using for your ajax call handling script.
return parseInt(data.toString(),10);
You cant return like that.
either assign in some global variable or do process there with data