I have an asynchronous jsonp-Call and try to assign the result to the variable "FILL_ME" in the example below.
The onSuccess function is called successful, nevertheless it is not possible to assign it's value to the variable "FILL_ME". Instead the error is thrown: Uncaught TypeError: Cannot read property '0' of undefined, which seems like a scope issue.
Please have a look at the following code.
The console.log("final " +FILL_ME) is triggered before the onSuccess method.
How would I assign the result to a variable?
function foo() {
var FILL_ME = 'OVERWRITE ME';
var $jsonp = (function() {
var that = {};
that.send = function(src, options) {
var callback_name = options.callbackName || 'jsonCallback',
on_success = options.onSuccess || function() {},
on_timeout = options.onTimeout || function() {},
timeout = options.timeout || 10; // sec
var timeout_trigger = window.setTimeout(function() {
window[callback_name] = function() {};
on_timeout();
}, timeout * 1000);
window[callback_name] = function(data) {
window.clearTimeout(timeout_trigger);
on_success(data);
}
var script = document.createElement('script');
script.type = 'text/javascript';
script.async = true;
script.src = src;
document.getElementsByTagName('head')[0].appendChild(script);
}
return that;
})();
$jsonp.send('https://run.plnkr.co/plunks/v8xyYN64V4nqCshgjKms/data-2.json', {
callbackName: 'jsonCallback',
onSuccess: function(json) {
console.log('onSuccess!' +json);
FILL_ME = json["sites"][0]["siteName"];
console.log(FILL_ME);
},
onTimeout: function() {
console.log('onTimeout!');
FILL_ME = '';
console.log(FILL_ME);
},
timeout: 5
});
console.log("final " +FILL_ME)
}
<body onLoad="foo()">
</body>