Chained JSON requests, making one optional/timeout

I have 3 json requests that need to happen consecutively.

app.request.json(webrequest1, function(data){
    // process 1

    app.request.json(localrequest2, function(data) {
        //process 2

        app.request.json(webrequest3, function(data) {
            //process 3
        }
    }
}

The first one is not critical however: I want the first request to timeout after a short period if not succeeding, and then carry on with the others.

I believe I could solve this by making the first request a proper ajax call app.request() and making it async: false, and timeout: 3000,
But the world seems really quite against making things synchronous like this.

Is there a more appropriate way?
Is the app.request.promise() useful here, and that is what I need to learn next? If it times out, does that count as an error/rejected?

function doRequest2And3() {
    app.request.json(localrequest2, function(data) {
        //process 2

        app.request.json(webrequest3, function(data) {
            //process 3
        }
    }
}

app.request.json(webrequest1, function(data){
  // process 1
  doRequest2And3();
}, function () {
  // error or timeout
  doRequest2And3();
})

Thanks for the reply. I had ended up going for something similar as a temporary solution, so very reassured to hear your suggestion! (Was expecting to have to change it all)

Questions that come up then:

  • Are the pre configured defaults for shorthand method app.request.json() the same as the defaults for the API app.request() ?
  • What is the default timeout setting, as you suggested that this would trigger the error function? Is it zero, and therefore doesn’t actually happen? Can the setting be changed, or do you need app.request() to achieve this?

This was my current solution below therefore, to get a timeout feature. But is there a more concise way?

  • I think this means I can safely have async: true.
  • I think this is correct use of adding the complete: function() and has the same result as your example (putting the function request at end of success and error)

app.request({

        url: webrequest1,
        cache: false,
        dataType: 'json',
        async: true,
        timeout: 3000,
        success: function(data){
            //set some variables from the request
        },
        error: function(){
            //set some default backup variables
        },
        complete: function(){
            doRequest2and3();
        }
 });

Defaults are different and there is no default timeout. If you need extra config just do app.request with custom options

Cool, thanks. I think I’ve got the right solution now then.