2014-03-29 44 views

回答

12

:我们可以把返回值在数组例如

var array = ['One', 'Two', 'Three']; 
var id = array[0]; 
var data = getData(id); 
for (var i = 1; i < array.length; i++) { 
    // Or only the last "i" will be used 
    (function (i) { 
     data = data.then(function() { 
      return getData(array[i]); 
     }); 
    }(i)); 
} 

// Also, see how better the getData can be. 
function getData(id) { 
    return $.ajax({ 
     url: 'http://example.com/' + id, 
     dataType: 'jsonp', 
    }).done(function(d) { 
     var response = d; 
     console.log(d); 
    }).fail(function() { 
     alert('ERROR'); 
    }); 
} 

顺便说一句,如果你使用正确的承诺库,如bluebird,你会使用下面的代码:

var array = ['One', 'Two', 'Three']; 
Promise.reduce(array, function(data, id) { 
    return data.promise.then(function(result) { 
     return { promise: getData(id), results: data.results.push(result) }; 
    }); 
}, []).then(function(data) { 
    console.log(data.results); // yay! 
}); 

function getData(id) { 
    return Promise.cast($.ajax({ 
     url: 'http://example.com/' + id, 
     dataType: 'jsonp', 
    }).done(function(d) { 
     var response = d; 
     console.log(d); 
    }).fail(function() { 
     alert('ERROR'); 
    })); 
} 

正如您所看到的,读取/写入的方式更简单。

9

大多数承诺库都有这个内置的jQuery?没有这么幸运了:

首先,你的函数返回一个承诺:

function getData(id) { 
     return $.ajax({ // note the return 
      url: 'http://example.com/'+id, 
      dataType: 'jsonp', 
      success: function (d) { 
       console.log(d); 
      }, 
      error: function() { 
       alert("ERROR") 
      } 
     }); 
} 

现在,你把它们连在使用.then调用一个循环。请注意,.then只有在前一个承诺完成后才会执行。所以他们将一个接一个地依次运行。

var array = ['One', 'Two', 'Three']; 
var p = $.when(1); // empty promise 
array.forEach(function(el){ 
    p = p.then(function(){ 
     return getData(el);; 
    }); 
}); 

所有功能将依次运行。还剩下什么?返回值。当前的实现丢弃返回值。该解决方案使用for

var array = ['One', 'Two', 'Three']; 
var p = $.when(1); // empty promise 
var results = []; 
array.forEach(function(el,index){ 
    p = p.then(function(){ 
     return getData(el); 
    }).then(function(data){ 
     results[index] = data; // save the data 
    }); 
}); 
p.then(function(){ 
    // all promises done, results contains the return values 
}); 

为什么停在那里,虽然,让我们把它更好的:)你的整个代码可以缩短到

["One","Two","Three"].map(makeUrl).map($.get).reduce(function(prev,cur,idx){ 
    return prev.then(cur).then(function(data){ results[idx] = data; }); 
},$.when(1)).then(function(){ 
    // results contains all responses here, all requests are sync 
}); 

function makeUrl(id){ 
    return "http://example.com"+id+"?callback=?"; 
} 
+0

你真的使用“缩短”这个词吗? –

+0

是的,我相信我做到了。 –