Get result from JavaScript Promise (.then function) when doing API call? [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'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
});
}

Related

What's the best way to have a JS function do a simple AJAX true/false request and return that result [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
What's the best way to have a JS function to do a simple AJAX true/false request and return that result.
I want to do a simple AJAX request, in a JS function, that checks if a users session is still active. The function should wait for the AJAX request to complete and return true or false.
I've achieved this using a setInterval but I don't think this is the best way. I tried to use jQuery $.when but I couldn't get the function to return a result.
function checkSessionIsStillActive(){
var result; //ajax result will be put in here. It will be undefined until ajax complete
$.getJSON('application/app_cfc/session_check.cfm/ajax')
.done(function( data ) {
// return the value
result = data.session_active;
});
// Do an interval loop check until the result is defined
var interval_check = setInterval(function(){
// Return the result as soon as we have it
if(result != undefined ){
// Clear this interval loop
clearInterval(interval_check);
// return the result to the calling function
return result;
}
}, 100);
}
You should read about async javascript, especially Promise.
function checkSessionIsStillActive(){
return new Promise((resolve, reject) => {
$.getJSON('application/app_cfc/session_check.cfm/ajax')
.done(data => {
// return the value
result = data.session_active;
resolve(result);
});
});
}
If you call the function you would then do
checkSessionIsStillActive().then(data => {
// result from function is available here
});
Use fetch() API and ASYNC code.
async function isSessionActive(url) {
let data = await fetch(url);
let jsonData = await data.json();
jsonData.sessionActive ? true : false;
}
let result = isSessionActive('application/app_cfc/session_check.cfm/ajax');
console.log(result) // either true or false

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

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);
}
}

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);
});

Return a nested function from inside a node module [duplicate]

This question already has answers here:
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 8 years ago.
I trigger a function using require() in my app.js file and the result returned is 'undefined'. I think this is due to the function being nested. What is the best way to return the nested value. I have tried the method below but the function appears to be asynchronous and the returned value is returned as undefined before the data is provided.
app sample code --
app.get("/twitter/:handle", function (req, res) {
var handle = req.params.handle;
var twitter = require('./module/twitter');
var data = twitter.searchHandle(handle);
console.log(data);
res.sendStatus(data);
});
module sample code -
var twitter = {
searchHandle: function(handle){
var dataToReturn;
T.get('search/tweets', { q: handle, count: 100 }, function(err, data, response) {
dataToReturn = data;
});
return(dataToReturn);
}
};
module.exports = twitter;
searchHandle is an async call. Returning dataToReturn will always be undefined as it's value has not yet been populated. You will need to pass a callback function to searchHandle to be executed once dataToReturn is populated.
//app.js
var handle = req.params.handle;
var twitter = require('./module/twitter');
var data = twitter.searchHandle(handle, function (data) {
console.log(data);
res.sendStatus(data);
});
//twitter.js
var twitter = {
searchHandle: function(handle, callback){
T.get('search/tweets', { q: handle, count: 100 }, function(err, data, response) {
callback(data);
});
}
};
module.exports = twitter;

Replace synchronous AJAX logic with asynchronous logic [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I was having an obsolete JS library which was making API call Synchronous for which I decided to write JS function which can make them Async using jQuery.
In the following code the getData function is to be a generic function which makes API calls according to params passed and then extract data from the received XML/JS.
The second call(getAllData2) needs values from the result set of getData so I need a callback kind of thing in which the subsequent call can be made after the data is available from the 1st call.
Can this be achieved without the ajax success call back as I want getData function to remain generic.
I had tried jQuery promises but that gives me the raw data of the call instead of the processed one which I will have to process in each of the done callback separtely.
getData(param1,param2..){
var retData = {};
......Param dependent code here..
jQuery.ajax({
url:....,
.......
success: function(resp){
if(resp.length > 0){
jQuery.each(resp,function(key,val){
var i = 0;
var retObj = {};
jQuery.each(val,function(k,v){
retObj[k] = v;
i++;
});
retData[key] = retObj;
});
}
---Process recieved XML/JS and Insert values in retData here--
}
});
return retData;
}
var getAllData = getData(x,y);
var getAllData2 = getData(a,b); // this call needs param from getAllData.
Please suggest.
Thanks
Promises are indeed what you should be using.
That will allow you to structure your logic like this:
function processResult(resp) {
var retData = {};
if(resp.length > 0){
jQuery.each(resp,function(key,val){
var retObj = {};
jQuery.each(val,function(k,v){
retObj[k] = v;
});
retData[key] = retObj;
});
}
return retData;
}
getData(x, y)
.then(function (result) {
var processed = processResult(result);
return getData(processed);
})
.then(function (result) { // result is the result of the second getData()
// use result
});
If you want to do pre-processing of the results in your getData() function, again you can do this with promises:
function getData(param1,param2..) {
......Param dependent code here..
return $.ajax({
url:....,
.......
})
.then(function (resp) {
var retData = {};
if(resp.length > 0){
$.each(resp,function(key,val){
var retObj = {};
$.each(val,function(k,v){
retObj[k] = v;
});
retData[key] = retObj;
});
}
return retData;
});
}
getData(x, y)
.then(function (processedResult) {
return getData(processedResult, otherParameter);
})
.then(function (processedResult2) {
// use processedResult2
});

Categories

Resources