I am making synchronous requests i.e. I always set {async: false}.
My problem is, while jQuery's $.ajax() returns whatever the response data I want it to return, AngularJs's $http() return a promise which is a big pain in my eyes.
Below, there's some code to demonstrate my problem.
This is jQuery:
// Library for sending $.ajax requests
Core.libs.prototype.send = function(...) {
var options = {
async: false,
// ...
};
return $.ajax(options).done(function(data) {
return data;
});
}
// Here I make requests
let rest = Core.libs.rest(...); // Get the library
let myVar = rest.send(...); // Make the request
console.log(myVar); // This returns an array from DB: [apple, orange] which is OK
And this is AngularJS:
// Library for sending $http requests
Core.libs.prototype.send = function(...) {
var options = {
async: false,
// ...
};
return $http(options).then(function(response) {
return response.data;
}, function(err) {
return err;
});
}
// Here I make requests
let rest = Core.libs.rest(...); // Get the library
let myVar = rest.send(...); // Make the request
console.log(myVar); // This returns a PROMISE which is not what I want
Is there a way how to modify Core.libs.prototype.send to return actual data instead of a promise?
I would like to avoid modifying anything else than the library method.
I do not want this solution, because then I would have to replace it everywhere in my code:
let rest = Core.libs.rest(...); // Get the library
let myVar = rest.send(...).then(data => data); // Make the request
console.log(myVar); // This returns [apple, orange] but I don't want this solution
I also tried this, but it's not working as expected:
// Library for sending $http requests
Core.libs.prototype.send = async function(...) {
var options = {
// ...
};
let res = await $http(options).then(function(response) {
return response.data;
}, function(err) {
return err;
});
return res;
}
// Here I make requests
let rest = Core.libs.rest(...); // Get the library
let myVar = rest.send(...); // Make the request
console.log(myVar); // This still returns a PROMISE. Why?
You should embrace promise/async await but that is not the point of your question. To achieve what you want, you either call using the async/await notation or then() clause, but not together:
// Library for sending $http requests
Core.libs.prototype.send = async function(...) {
var options = {
// ...
};
try {
const response = await $http(options);
return response.data;
} catch (err) {
return err;
}
}