0

I am trying to chain some events together so that each function will run after the previous one has finished. This is how I have it:

function siteUsage() {
    // Do Something
}
function siteTerms() {
    // Do Something
}
function siteSources() {
    // Do Something
}

siteUsage().then(siteTerms()).then(siteSources());

But I get this error:

Uncaught TypeError: Cannot call method 'then' of undefined 

Any ideas? Am I also going about this the right way, I mean chaining Ajax requests like this?

EDIT

Here is one of the functions in its entirety. Incase you need to see what it does.

function siteUsage() {

        $.getJSON('charts_ajax.php',{a : 'visits', rangeStartDate : '<?=$_POST["rangeStartDate"] ?>', rangeEndDate : '<?= $_POST["rangeEndDate"] ?>'}, function(data){
            if(data){
                var tableHtml = '<tbody><tr><td class="id" width="20%">Visits</td><td width="20%">' + data.visits + '</td><td width="60%">A visit is a single-user session.</td></tr>' +
                    '<tr><td class="id">New Visits</td><td width="20%">' + data.newVisits + '%</td><td>The percentage of visits marked as first-time visits.</td></tr></tbody>' +
                    '<tr><td class="id">Page Views</td><td>' + data.pageViews + '</td><td>Views of each individual page.</td></tr>' +
                    '<tr><td class="id">Average Pages per Visit</td><td>' +  data.avgPageViews + '</td><td>Page Views divided by Visits</td></tr>' +
                    '<tr><td class="id">Average Time On Site</td><td>' + data.avgTime + '</td><td>The average duration of visitor sessions.</td></tr>' +
                    '<tr><td class="id">Visitors</td><td>' + data.totalVisits + '</td><td>Total number of visitors to your website for the requested time period.</td></tr>' +
                    '<tr><td class="id">Visits from Mobile Devices</td><td colspan="2"><div style="position:relative; background:#9fb7cb; height:22px;"><span style="width:' + data.yesMobile + '%; background:#003F75; height:22px; display:inline-block; border-right:1px solid #fff;"></span><span style="font-size:85%; position:absolute; left:8px; top:4px; color:#fff; text-shadow:0 1px 0 #003F75; width:80px;"><strong>Yes:</strong> ' + data.yesMobile + '</span><span style="font-size:85%; position:absolute; right:8px; top:4px; color:#003F75;"><strong>No: </strong>' + data.noMobile + '</span></div></td></tr>';

                $('#usage-table').html(tableHtml).find('.spinner').stop();

            }
        });

    }
4

1 回答 1

4

siteUsage 必须返回一个承诺对象或一个延迟对象。例如,

function siteUsage() {
    return $.getJSON(...);
}
function siteTerms() {
    return $.getJSON(...);
}
function siteSources() {
    return $.getJSON(...);
}

siteUsage().then(siteTerms).then(siteSources);

此外,正如您在我的代码中看到的那样, .then 接受一个函数,因此您需要传递函数而不是执行它(除非函数返回一个函数,这对于这个用例来说不太可能)

于 2013-11-13T15:03:59.450 回答