2014-03-29 3 views

답변

12

을 단축 할 수 있도록하자,

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

왜하지만 거기서 멈추지 : 우리는 예를 들어 배열에 반환 값을 넣을 수 있습니다

을 그런데
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를 사용의 그것이 더 좋은 :) 귀하의 전체 코드가

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

예, 제가 그랬다고 믿습니다. –