How to get a value from a callback? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I have this line of codes:
let message = channel.consume(queue, msg => {
console.log('Return this in the "message" variable', msg.content);
});
When I tried to log the value of message, it does not equate to msg.content but it gets the value from the return of consume method. What's the workaround in order for me to get the right value from the callback.
Thanks

var message;
channel.consume(queue, msg => { message = msg.content; });
Not really sure what you're asking, but are you trying to set message within the callback? If so, see above.

You cannot "return" the value of the callback. Also, there's little point in doing so since the line after that code will execute before the callback has even executed.
While it's not "returning" the value, you can use a Promise.
If you can transpile from ES7, you can use async-await which allows you to call asynchronous functions using synchronous-looking code within an async function using await.

Related

How to show data outside of a subscribe scope/ how to use callback [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)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to show a list from an API call.
let url = 'api/list';
this.apiService.get<List[]>(url)
.subscribe((response) => {
this.list = response; // response has data
})
console.log(this.list); // no data shown
Because of async behavior the console always shows a blank list. How can I show the list with data outside of the subscribe scope. For clarification I need the list with data in the consoles position. I am familiar with the concept of callback. Do I need to use a callback function here? If yes, how can I achieve that?
The object the keyword this is pointing to is different in the places you are using it. So when you are setting this.list inside your callback function, you are setting the attribute list of your callback function.
One old skool way to fix this would be setting let that = this and then inside your callback function using that.list. By doing so you would be setting the attribute list of the keyword this that is one level above your callback function.
Hope it still makes some kind of sense.
Also look at Andrew Hills comment, it's full of logic :)

Jquery GET in plain javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I call my_function on form submit. The function looks inside a text file for the number entered by the user in my_input. If this number does not exist, the function pops an alert and should stop form submit.
My problem: the alert is shown, but when I close it, the form gets submitted. My problem is similar with this thread: How do I return the response from an asynchronous call?
One of the solutions there is to do the GET in plain javascript. Can someone help please? This is too advanced for me.
function my_function() {
$.get("http://www.example.com/file.txt", function(contents) {
var my_number = document.getElementById("my_input").value;
var hasString = contents.includes(my_number);
});
console.log(hasString); // **ALWAYS RETURNS UNDEFINED**
if (hasString == false) {
alert('Number does not exist in text file!');
return false;
}
}
hasString is a local variable of the callback function provided to $.get as second argument. This is why it's undefined outside said function. Note just moving the variable declaration to the outer scope won't fix the problem, as the callback function will be executed after the check hasString == false anyway (it will be executed when the get request finishes).
Answering your question more directly: either perform the get request synchronously (and properly declare the variable in the scope you need to use it) or restructure your code to use the information retrieved by the get request only inside the callback. Read the post #abc123 mentions for more information.

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.

Trying to access a variable inside a jquery function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I am trying to access a variables inside a $.post jquery method. The code I have so far is below:
var fromDatabase;
$.post( "../read.php", function( data ) {
fromDatabase = JSON.parse(data);
console.log(fromDatabase); //this works fine
return fromDatabase;
});
console.log(fromDatabase); // but this gives me 0.
I am trying to get the from database variable so i tried to declare it outside the function to no avail.
Thank you.
You can't - you must continue program execution from within the callback, not immediately after the asynchronous $.post call.
You cannot return from an asynchronous function, that's the nature of asynchronicity. Instead, after your value is available (the callback function is called) you must work with the data within the scope of that function.
Perhaps a good starting point would be some Ajax tutorial. If you want more, simply google for JavaScript async.

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