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 function and a loop:
var songs = Musics.searchSongs(query).then(function(rs) {
return rs;
});
for (var i = 0; i < songs.length; i++) {
console.log(songs[i]);
}
Now I want to run the loop with the result that taken from after executing the function. How can I do that?
You cannot return from an asynchronous call. You can, however, pass in a callback function to an asynchronous call, and pass the result of the call to that callback function.
So, in your case, you could create a function that receives an array of songs, and loops through each song, logging each to the console. You would then pass that function as a parameter to your asynchronous call.
function callback(songs) {
for (var i = 0; i < songs.length; i++) {
console.log(songs[i]);
}
};
Musics.searchSongs(query, callback).then(function(rs) {
callback(rs);
};
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I have this problem, when I change the value of a variable inside my function if i want to use it outside of it, the vaalue of the variable returns to 0, but inside of it, the value it's changed.
I need to know a way to keep the value of the variable outside the function.
Here is my current code:
function getCarsWithNoStatus() {
var statusName = [];
// We set the total counters for the areas
var totals = {bodyshop: 0, paintshop: 0, assembly: 0};
// var tmpTotal = 0;
WebApiFactory.getNoStatusOrders(bodyShop1).then(function(statusMonData) {
for(var statusProperty in statusMonData.NoStatusOrders) {
statusName = statusProperty;
for (var j = 0; j < statusMonData.NoStatusOrders[statusName].length; j++) {
if (typeof statusMonData.NoStatusOrders[statusProperty][j] !== null) {
totals.bodyshop++;
console.log(totals.bodyshop); //here shows correct value
}
}
}
});
console.log(totals.bodyshop); //value returns to 0
}
The value of totals is being modified in an asynchronous code, so your console.log is being executed before the asynchronous code is finished. When working with such code you usually want to return a Promise or execute a callback after the async code is finished executing.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why are AngularJS $http success/error methods deprecated? Removed from v1.6?
(2 answers)
Closed 5 years ago.
I have function in angularJS invoked when clicked, I am also calling another service function inside that function, which is going to change some values for later use in first function.
Problem statement: Function getData finishes first with retrning model, and after it finishes it all process then calll getDetails. I want to make this call in sequence.
this.getData = function () {
var a = '';
var b = '';
var c = '';
//I want this call to be finished before above function
MyServices.getDetails(id, type)
.success(function(data, status, headers, config){
if(status == '200'){
// my code goes here to change some values
})
}
var model = [];
retrun model
};
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 6 years ago.
So the for loop runs if I replace$.get('/preceed_with_an.txt', function(data){var ans = data.split('\n')}); with ans = ["filler","more filler"] but when the $.get line is in it refuses to execute the for loop and nothing is ever written to the console. For context, I am writing code that tells you if you should use A or AN before a word. Words that you use an for are all on separate lines in preceed_with_an.txt I have checked an the $.get functions and the file is written to the array just fine.
$(document).on('input',$('#givenWord'),function(){
var ans = new Array;
$.get('/preceed_with_an.txt', function(data){var ans = data.split('\n')});
for (var i = 0; i < ans.length; i++){
console.log("help");
if (ans[i] == $('#givenWord').lower){
var answer = $("#answer");
console.log("AN");
$(answer).text("An");
break;
}else{
var answer = $("#answer");
console.log("A")
$(answer).text("A");
}
}
});
The get() is asynchronous, so ans.length is equal to zero because the data return after the for loop execution.
You have to execute the for loop in the get() callback function:
$.get(url, function(data) {
var arr = data.split(',');
for(...) {
//...
}
});
Execution flow (your code)
Create ans array
Call the get() function
Try to execute the for loop (without available data)
get() return the data
Asynchronous call
Create ans array
Call the get() function with the for loop in the callback
get() returns data and executes the callback --> for loop with data
EXAMPLE
Check the console for the results. Even if the setTimeout function is called before the console.log(), the code continued the execution and waited for the callback's answer (after 1 second). When the result came out, the callback executed:
var def = $.Deferred();
def.done(function(data) {
console.log(data);
});
//Asynchronus call (delays for 1 second)
setTimeout(function() {
def.resolve('Callback after 1 second')
}, 1000);
//Execute immediately
console.log('Write something!');
//Console results
// 1. Write something
// 2. callback (after 1 second)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Check these links about asynchronous functions:
jQuery.get()
Async
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.
I have had a look, and see some great examples of nesting functions, but even with reading them, I cannot see why I am getting undefined when i call this function:
function readBttnDetec() {
var devid = localStorage.getItem('vBttn');
var bd = 0;
bd = ble.read(devid, 'fffffff0-00f7-4000-b000-000000000000',
'FFFFFFF2-00F7-4000-B000-000000000000',
function(t) {
var data = new Uint8Array(t)
console.log('returns: ' + data[0]); // this returns 6
return data[0];
}, function(f) {
console.log(f);
});
return bd;
}
This is the call:
//check button state
var detecs = readBttnDetec();
console.log(detecs);
if(detecs == 2) {
// fall detection disabled
$('#playfall').removeClass('km-state-active');
} else if(detecs == 6) {
// fall detection enabled
$('#playfall').addClass('km-state-active');
} else {
// error reading button
}
I am missing something simple I am sure of it, but I cannot see it.
Thanks in advance
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I made a function that runs a get request using JQuery.
But I need the get to return this received value to the calling function. function
gettime() {
var timeOut =0;
$.get("http://localhost:8080/t.html", function( data )
{
timeOut = data*1000;
return timeOut;
});
//retun(timeOut);
}
I want the value received by get to be returned to the main function that calls gettime()
please help out.
It's a integer am passing.
An idea could be implementing a callback:
function gettime(callback) {
var timeOut =0;
$.get("http://localhost:8080/t.html", function(data)
{
timeOut = data*1000;
callback(timeOut);
});
}
//Then you can retrieve that value by doing this:
gettime(function(timeout){
//Do your stuff here.
});