I am trying to connect to server and wait for the server to response then do some actions. Here is what I am trying to do :-
function connect(someArg){
// somecode...
// then it calls a function from client side and that function checks the
//server response messages let's call it and create a sample of that function
//bellow
checkServerMessages();
}
function checkServerMessages() {
// some code to show and check on server response messages
}
function f1(){
// some code...
return response
}
// HERE THE FIRST CALL STARTS
f1()
.then(function(response){
connect();
// I am not explicitly returning anything
// what I am trying to do is here, if I use setTimeout it works but I need to
// change the setTimeout function to a nested promise
//.then(function() { // I tried this but it didn't work
setTimout(function() {
// some code... some values will change after the connect function is
// implemented then I use those values here and change some button captions
// and some simple actions which are not really related to connect function
// except the token and session id and some other variables
});
})
.catch(function(error) {
console.log(error);
}
Thanks in advance and please let me know if my question is not clear.
If I recall correctly, jQuery’s $.ajax doesn’t return a promise, so you can’t chain the response with .then()
Instead, you write a callback function for the success condition of the response.
If you use the new native fetch() API, that is ‘thenable’ (it returns a promise and can be chained), but it doesn’t work in older browsers and needs polyfills if you need to support them.
yes I am using JQuery’s $.ajax and everything is fine I guess. I am getting the response back. My problem is not there. It’s when I call connec() function then it will talk to server and get a response back from server. everything is fine till here … after I call the connect(), I need to wait for the response I will be getting from server and that’s where I need to right a promise/callback because, some variables will change if I wait for server response and then I need to continue based on server response but, because my promise doesn’t work so I used a bad way to handle this waiting which is (setTimeout) and that’s not a solution. So, I need to figure that promise thing out or callbacks but, I am not really familiar with callbacks.