How to return the response from multiple asynchronous function calls?
本问题已经有最佳答案,请猛点这里访问。
我有一个函数,我做了多个异步函数调用。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | var publicationData = new Array(); var researchers = []; var year = []; var title = []; var pub = []; var dataJson = []; callServerAsync(); function callServerAsync(){ $.get('Year2014.html').then(function(responseData) { var result1 = handleData(responseData, dataJson); }); $.get('tauchi_publications.html').then(function(responseData) { var result2 = handleData(responseData, dataJson); }); //TO-DO //draw(result1, result2); } function handleData(responseData, dataJson){ var htmlObject = document.createElement('div'); htmlObject.innerHTML = responseData; pub = htmlObject.getElementsByClassName("julkaisu"); getPublicationData(pub); getResearchersYearTitle(publicationData); dataJson = createJson(researchers,year,title); return dataJson; } function draw(result1,result2){ result1.concat(result2); } |
使用承诺! jQuery的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | function callServerAsync(){ var p1 = $.get('Year2014.html').then(function(responseData) { return handleData(responseData, dataJson); }); var p2 = $.get('tauchi_publications.html').then(function(responseData) { return handleData(responseData, dataJson); }); // the `return` here is just for good measure return $.when(p1, p2).then(function(result1, result2){ // all your data available, can use it here. // It's in the function arguments draw(result1, result2); }); } |
我想你可以做这样的事情。 当呼叫结束时,它会检查其他呼叫/结果是否存在,如果不存在,则不执行任何操作。 这样最后一个函数实际上会绘制它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | function callServerAsync(){ var result1, result2; $.get('Year2014.html').then(function(responseData) { result1 = handleData(responseData, dataJson); if(result1 && result2) { draw(result1, result2); } }); $.get('tauchi_publications.html').then(function(responseData) { result2 = handleData(responseData, dataJson); if(result1 && result2) { draw(result1, result2); } }); } |