I have some Javascript code that is similar to the following:
var Requests = {
get: function(search) {
// HTTP request happens, returns data.
}
}
I'm trying to invoke this somewhere else, like the following:
Requests.get('thing');
Although this is returning undefined because it's not waiting for the http request result. I'm wondering how I can defer this request until it's successful, or somehow check for a callback in the invoking code. Thanks!
You need a promise. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise
var Requests = {
get: function(search){
return new Promise(resolve,reject){
//if it does what you want
if(data) resolve(data)
else reject(error)
}
}
}
And then
Requests.get('thing').then('do something else')
The other option is to use await/async but that is not fully supported yet. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
The function can return a promise:
var Requests = {
get: function(search) {
return new Promise(function(resolve, reject){
// call resolve in case of success, and reject in case of error
})
}
}
Requests.get('thing').then(
function(response){
// success
},
function(error){
// something went wrong
}
);
In the "then" method of a Promise object, you need to pass the two functions used when the promise is resolved or rejected.
For more information on Promises: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.