简体   繁体   中英

Can't implement deferred promise in jquery ajax

I'm struggling to implement deferred to get async ajax response. I have this setup:

report.js

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

index.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>

Currently I get "undefined" returned straight away because the alert box doesn't wait for the ajax function to run. Using some tutorials online i've tried to implement it this way:

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

index.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>

I've obviously made a few mistakes on the way because I'm getting the errors below and I can't seem to get past it:

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

I think the addition of the deferred object in getReport is unnecessary because $.ajax already creates one for you. It might be better to modify your original code this way:

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

then in your index file:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM