Make return call from nested function [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
function runimage(){
var vel = val.id;
var secondlink = 'someurl'+vel+'stuff';
$.getJSON(secondlink, function(beyta){
var target = beyta.attachments.data[0].media.image.src;
return target;
});
return "FISH";
}
I am making an API call via jQuery's getJSON method. The problem I am having is getting the runimage() function return the value of my target value.
The code return target gives me undefined. This is the result even if I place a dummy string in place of target.
To see if this is a problem with closures, I added a dummy return "FISH" outside of my getJSON call, and the code does indeed return "FISH"
How would I go about getting runimage() to return the value of variable target?

The issue is that while you are waiting to get your AJAX response, the function has already returned "FISH".

Related

JavaScript - Problem getting data from promise object [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
So, I'm new to using promise object... I'm trying to make a Facebook instant game which uses the function FBInstant.player.getDataAsync().then(). This function returns a promise and I have no clue how to use the data returned other than with console.log(). If I try to insert the data to a defined variable it becomes unidentified.
Example:
User = [];
FBInstant.player.getDataAsync(['name']).then(function(data) {
User['name'] = data['name'];
});
console.log(User['name']) // return unidentified.
Sorry for my poor explanation I'm new to this and I'm just trying to accomplish a simple task.
User = [];
FBInstant.player.getDataAsync(['name']).then(function(data) {
User['name'] = data['name'];
console.log(User['name'])
});
This should give you a response

Bind a Promise return inside a get function [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 5 years ago.
Hello im new in typeScript and Angular.
I need to get a value in storage, the storage.get return a promise, so i try:
getNomeUsuario():string{
var that = this;
this.storage.get('nomeUsuario').then(function(nome){
that.nomeUsuario = nome;
}.bind(this));
return this.nomeUsuario;
}
The problem is that always return a undefined.
I also get the same with an arrow function.
getNomeUsuario():string{
this.storage.get('nomeUsuario').then((nome)=>{
this.nomeUsuario = nome;
});
return this.nomeUsuario;
}
How can I return the nome value ?
Sorry about my English hehe
Since this.storage.get("nomeUsuario") is asynchronous, there's no way the getNomeUsuario() method can return it's value without returning a Promise, so you'll need to do it like this:
getNomeUsuario(): Promise<string> {
return this.storage.get("nomeUsuario");
}
And handle the Promise where you call getNomeUsuario().
ps: you could also use an Observable, but it would add complexity without any benefits.
this.storage.get('nomeUsuario') executes asynchronously, and when you returns that.nomeUsuario, the promise wasn't executed yet and that.nomeUsuario still undefined. Try to insert this return into .then section like this:
getNomeUsuario():string{
var that = this;
this.storage.get('nomeUsuario').then((nome)=>{
that.nomeUsuario = nome;
return that.nomeUsuario;
});
}

JavaScript function returns empty string when a value is expected [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
There's probably an obvious mistake somewhere, but I just can't out find what's wrong.
I'm trying to retrieve data from an api, and use the js-function below to get it. If I do an alert(key) on the data inside the $.get-function, it alerts the correct data.
function getApiKey(company, password) {
var url = "http://myapi.com/" +company+ "?password=" +password;
var key = "";
$.get(url).done(function(data) {
key = data;
//alert(key) returns the correct data
});
return key;
}
However, I need to use the function in a different file, and that's where it doesn't work. When I do
var key = getApiKey("company", "password");
alert(key);
key is empty.
The $.get command is asynchronous, meaning that your function returns key with its initial value of "", then later when the async callback fires, it runs key=data.
You should read up on asynchronous behaviour in javascript - for a solution, you'll need some way to get the data back to the place of the call asynchronously. One such option is a promise.

Ajax .responseText is available in alert but does not get saved in variable or return [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
var response_var=""; // Added this line for debugging
ajax.onreadystatechange=function()
{
if(ajax.readyState==4 & ajax.status==200)
{
response_var=(ajax.responseText);
alert(ajax.responseText); // This alerts properly (some text).
return (ajax.responseText); // This is returning as undefined
}
}
return response_var; // This is empty if I add the line 1, if not in console it gives error response_var is not defined.
Why does not the response is getting stored in the variable or returned? I guess the scope of response_var ends within the onreadystatechange function so I tried return. But the value is undefined.
Ajax function always work out of sync with normal code flow ,hence the name "Asynchronous JavaScript and XML" .For Ajax required events you should not rely on return ,rather do your task immediately when you get your response from AJAX.

Getting a Javascript variable out of a $.get statement [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
EDIT: Please feel free to delete, I have found an appropriate answer in the duplicates mentioned above. Apologies.
I have the following code, and can't seem to dig the variables out correcly:
$('#button').click(function() {
alert(getRemaining(0));
}
function getRemaining(i){
var x;
$.get('files/remaining.txt', function(file){
x = file.split(",");
});
return x[i]
}
My alert just keeps coming out as undefined. What am I doing wrong?
the .get that you run is an asynchronous function. This means that execution of your code will continue on past it BEFORE it completes. The callback function that you pass into .get will be called once it is finished (this is the main reason for providing a callback).
This code will alert once the .get has returned.
$.get('files/remaining.txt', function(file){
x = file.split(",");
alert(x[0]);
});

Categories

Resources