2016-01-11 79 views
2
function sync(){ 
    var timer; 
    $('#result').html('waiting…'); 
    var promise = process(); 
    promise.done(function(a) { 
     $('#result').html('done.'+a); 
    }); 
    promise.fail(function(e) { 
     $('#result').html('fail.'+e); 
    }); 
} 

function process() { 
    var deferred = $.Deferred(); 
    var url = "https://maps.googleapis.com/maps/api/geocode/json"; 
    $.ajax({ 
     url: url, 
     data: {}, 
     success: function(data){ 
      return deferred.resolve(5); // line:1 
     }, 
     error: function(data){ 
      return deferred.reject(0); // line:2 
     } 
    }); 
    return deferred.promise(); // line:3 
} 

为什么要在上面的代码中返回deferred.promise()?假设如果我删除线#3,然后我得到这样一个错误:我们为什么要返回deferred.promise()

TypeError: promise is undefined

应该在line#1line#2返回。为什么我们需要line#3以及第3行的用途是什么?

if it is return properly at line#1 or Line#2 then What is the use of line#3 see the code here

回答

0
function process() { 
    var deferred = $.Deferred(); 
    var url = "https://maps.googleapis.com/maps/api/geocode/json"; 
    $.ajax({ 
     url: url, 
     data: {}, 
     success: function(data){ 
      deferred.resolve(); // line:1 
     }, 
     error: function(data){ 
      deferred.reject(); // line:2 
     } 
    }); 
    return deferred; // line:3 
} 

因为上下文是“窗口”内阿贾克斯request.you可以试试这个没有在$就回调返回任何东西:

function sync(){ 
    var promise = process(); 
    promise.done(function() { 
     alert('done.'); 
    }); 
    promise.fail(function() { 
     alert('fail.'); 
    }); 
} 
function process() { 
    var deferred = $.Deferred(); 
    var url = "https://maps.googleapis.com/maps/api/geocode/json"; 
    setTimeout(function(){ 
     if(true){ 
      deferred.resolve(); 
     } 
    },3000); 
    return deferred; // line:3 
} 

这就是你们的榜样的模拟。