How do I wait for a promise to finish before returning the variable of a function?
Instead of returning a resultsArray
you return a promise for a results array and then then
that on the call site - this has the added benefit of the caller knowing the function is performing asynchronous I/O. Coding concurrency in JavaScript is based on that - you might want to read this question to get a broader idea:
function resultsByName(name)
{
var Card = Parse.Object.extend("Card");
var query = new Parse.Query(Card);
query.equalTo("name", name.toString());
var resultsArray = [];
return query.find({});
}
// later
resultsByName("Some Name").then(function(results){
// access results here by chaining to the returned promise
});
You can see more examples of using parse promises with queries in Parse's own blog post about it.
How to return value from an asynchronous callback function?
This is impossible as you cannot return from an asynchronous call inside a synchronous method.
In this case you need to pass a callback to foo that will receive the return value
function foo(address, fn){
geocoder.geocode( { 'address': address}, function(results, status) {
fn(results[0].geometry.location);
});
}
foo("address", function(location){
alert(location); // this is where you get the return value
});
The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.
If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.
Variables are not being set inside the .then() part of a Promise
return
the value at function passed to .then()
var storedUserID = ROBLOX.getIdFromUsername(accountArg)
.then(function(userID) {
return userID;
});
you can then use or change the Promise
value when necessary
storedUserID = storedUserID.then(id) {
return /* change value of Promise `storedUserID` here */
});
access and pass the value to message.reply()
within .then()
storedUserID.then(function(id) {
message.reply(id);
});
or
var storedUserID = ROBLOX.getIdFromUsername(accountArg);
// later in code
storedUserID.then(function(id) {
message.reply(id);
});
Related Topics
Shiny App:Disable Downloadbutton
How to Detect Faces Using Ruby
How to Auto Hide Alert Box After It Showing It
Passing Variable from JavaScript to Ruby on Rails
Is There a Jquery Autogrow Plugin for Text Fields
Can Nokogiri Interpret JavaScript? - Web Scraping
Mixing Jsf El in a JavaScript File
Why Doesn't Decodeuri("A+B") == "A B"
Get Number Days in a Specified Month Using JavaScript
Anything Similar in JavaScript to Ruby's #{Value} (String Interpolation)
Websocket Handshake with Ruby and Em::Websocket::Server
How to Write a Script to Edit a JSON File