When my JavaScript is run it will call the getDoctorComplete function. When the AJAX request is completed, it will set a = chelsea. Otherwise, there will be a trigger change and will run $('#dropdown_hosp').change(.... In the $('#dropdown_hosp').change(..., it will call the getSpecialty function. When the AJAX request is completed with the getSpecialty function, I want to get the value of a. I console.log it, but it contains an empty string. How can I solve this problem?
var a = ''; $(document).ready(function () { app.getHospital({ areaId: '' }); app.getDoctorComplete({ doctorId: doctorId, doctorel: $('#dropdown_doct') }); $('#dropdown_hosp').change(function () { var dropdownspecialty = $('#dropdown_spec'); app.getSpecialty({ hospitalId: $('#dropdown_hosp').val(), apiUrl: 'api', special: dropdownSpec }); }); }); app = function () { function getHospital({ areaId }) { // ... $.ajax({ // ... success: function (result) { // ... }, // ... }).done(function () { $('#dropdown_hosp').select2(); }); }; function getSpecialty({ hospitalId, apiUrl, special }) { // ... $.ajax({ // ... }).done(function () { // test here console.log(a); }); }; function getDoctorComplete({ schdoctor_id, doctorel }) { // ... $.ajax({ // ... success: function (result) { // ... }, // ... }).done(function () { // ... a = 'chelsea'; b = '..'; $('#dropdown_hosp').val(b).trigger('change'); }); }; return { getSpecialty: getSpecialty, getDoctorComplete: getDoctorComplete } }();
Promise, resolve that Promise in thedonemethod and call.then()after the call, likeapp.getDoctorComplete( ... ).then(() => { Do something after the call here }).