首页 > 解决方案 > 无法在 jquery ajax 中实现延迟承诺

问题描述

我正在努力实现延迟以获得异步 ajax 响应。我有这个设置:

报告.js

function getReport(ref)
{
   $.ajax({
        url: "report.php", 
        dataType: 'json',
        data: { 
            ref: ref,
        },
        success: function(result){
           return (result);
           }
         }
    });
}

索引.html

<script>
function firstFunction() {
console.log ("start");
getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
var test = firstFunction();
alert(test);
</script>

目前我得到“未定义”立即返回,因为警报框不等待 ajax 函数运行。使用一些在线教程,我尝试以这种方式实现它:

报告.js

function getReport(ref)
{
   var deferred = $.Deferred();
   $.ajax({
        url: "report.php", 
        dataType: 'json',
        data: { 
            ref: ref,
        },
        success: function(result){
           deferred.resolve(result);
           }
         }
    });
  returned deferred.promise();
}

索引.html

    <script>
    function firstFunction() {
    console.log ("start");
    getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
    };
$.when(getData()).done(function(value) {
    alert(value);
});

getData().then(function(value) {
    alert(value);
});
</script>

我显然在路上犯了一些错误,因为我得到了以下错误,我似乎无法克服它:

Uncaught SyntaxError: Unexpected identifier
index2.html:12 start
index2.html:13 Uncaught ReferenceError: getReport is not defined
    at firstFunction (index2.html:13)
    at index2.html:16

标签: javascriptjqueryajaxpromise

解决方案


我认为deferred在 getReport 中添加对象是不必要的,因为$.ajax已经为您创建了一个。以这种方式修改原始代码可能会更好:

function getReport(ref)
{
   return $.ajax({ // Return the deferred object here. It is returned by .ajax()
        url: "report.php", 
        dataType: 'json',
        data: { 
            ref: ref,
        } // Remove the callback here. 
          // You cannot call return in the way you're trying here. 
          // The context is different and outside of normal flow.
    });
}

然后在您的索引文件中:

<script>
function firstFunction() {
  console.log ("start");
  // You must return the returned value here as well, otherwise variable `test` is going to be undefined.
  return getReport(2, 'queue', 'hour', '2018-09-09', '2018-09-10', 'pageviews', 'page', 's1390_5bbb4639ff37');
};
var test = firstFunction(); // test is now a deferred object
test.done(function(data) {
  alert(data);
});
</script>

推荐阅读