未捕获的类型错误:无法调用未定义的方法“then”

Uncaught TypeError: Cannot call method 'then' of undefined

本文关键字:未定义 调用 方法 then 类型 错误      更新时间:2023-09-26

我正在尝试将一些事件链接在一起,以便每个函数在前一个函数完成后运行。这就是我的方式:

function siteUsage() {
    // Do Something
}
function siteTerms() {
    // Do Something
}
function siteSources() {
    // Do Something
}
siteUsage().then(siteTerms()).then(siteSources());

但是我收到此错误:

Uncaught TypeError: Cannot call method 'then' of undefined 

有什么想法吗?我是否也以正确的方式做到这一点,我的意思是像这样链接 Ajax 请求?

编辑

这是整个功能之一。如果您需要查看它的作用。

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();
            }
        });
    }

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

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

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