Reputation: 59
I want a script file just for accessing a JSON from a url. I want to have a method to return the JSON object from the script into a var in a separate script file then modify it accordingly. Obviously since javascript is asynchronous it fails if I simply write it out. Therefore I must use a promise:
var promise1 = new Promise(function(resolve, reject) {
access(userSearchText); //send user input to get appropriate JSON object
});
promise1.then(function(value) {
var getData = returnData(); //method that returns JSON object from the other script
alert(getData); //print out the returned JSON object
console.log("we have finished");
});
But this is not printing out anything. The alert does not occur at all and nothing is being printed in the console. I am using jquery to access the url in the other script and I have a .done after accessing it in the script for retrieving the JSON as: access.js
var sendData;
(function() {
jqxhr = $.getJSON( url, {
})
.done(function( data ) {
sendData = data;
});
})();
function returnData(){
return sendData;
}
So there should not be any asynchronous issues in the script for accessing the URL because of .done. I really don't understand why this isn't working. I inspected my page and there are no errors to be seen anywhere. Can anyone help?
Upvotes: 0
Views: 1677
Reputation: 708026
promise1
never gets resolved.
In your definition of promise1
, you never call the resolve()
function to resolve it. Thus, it's .then()
never gets called.
Manually created promises are only resolved when you explicitly call resolve()
in the executor function.
If access()
is itself asynchronous, then we will need to more about that function to help you do this correct. Wrapping a promise around it does not do anything to help you. If access()
itself returns a promise, you should just use that promise and not wrap one around it.
Probably access()
should return a promise that is resolved when it's asynchronous operation is done and then you can do:
access().then(...).catch(...);
And, not wrap it with another promise.
The sendData
and returnData()
stuff just looks wrong. You'd have to explain and show more context to know what exactly the recommend.
Upvotes: 1