Fetching AJAX results from three endpoints, with error handling I have a requirement in which I need to get data by making AJAX calls. First search for data in endPoint1, if not found then in endPoint2, if not found then in endPoint3. But if any of the endPoint returns data, then there is no need to make further REST calls. 

I have achieved the functionality, but the code looks spaghetti.

If possible, please suggest a better approach to reduce this call indentation.

function myAjaxFunction(endPoint) {
    // returns promise 
}

function checkForData() {
    myAjaxFunction(endPoint1)
        .then(function (data) {
            if (data.d.results.length &gt; 0) { return "Data found"; }
            else {
                myAjaxFunction(endPoint2)
                    .then(function (data) {
                        if (data.d.results.length &gt; 0) { return "Data found"; }
                        else {
                            myAjaxFunction(endPoint3)
                                .then(function (data) {
                                    if (data.d.results.length &gt; 0) { return "Data found"; }
                                    else {
                                        console.info("sorry data not exist");
                                    }
                                }, function (e) {
                                    console.error()
                                });
                        }
                    }, function (e) {
                        console.error()
                    });
            }
        },
        function (data) {
            if (data.d.results.length &gt; 0) { return "Data found"; }
            else {
                return "not found.";
            }
        });
}
I would suggest passing in an array of endpoints so you can have one loop that calls an endpoint and looks at the result without repeating any code:

function checkForData(endPoints) {
    let i = 0;

    function next() {
        if (i &lt; endPoints.length) {
            return myAjaxFunction(endPoints[i++]).then(function(data) {
                if (data &amp;&amp; data.d &amp;&amp; data.d.results &amp;&amp; data.d.results.length &gt; 0) {
                    return data.d.results;
                } else {
                    return next();
                }
            });
        } else {
            return null;
        }
    }

    return Promise.resolve().then(next);
}

checkForData([endPoint1, endPoint2, endPoint3]).then(function(result) {
    // result here
    if (result) {
        console.log(result);
    } else {
        console.log("no data found");
    }
}).catch(function(err) {
    // error here
});


Note: I also put .then() on the same line as its parent function to avoid an extra level of indent.