1. 程式人生 > 其它 >js 解決在for迴圈中呼叫ajax,並等待返回結果後才進行下一次迴圈

js 解決在for迴圈中呼叫ajax,並等待返回結果後才進行下一次迴圈

技術標籤:JavaScriptjsajaxjavascript前端jquery

方式一 遞迴

 let arr = [];
 (function loop(index) {
     if (index >= 0) {//遞迴終止條件
     	//模仿ajax請求
         setTimeout(() => { //一次回撥完成才進行下一次回撥
             arr.push(index * 1000);
             loop(--index);
         }, index * 1000);
     } else {
         console.
log('遞迴方式結果:',arr); } })(3)

測試結果:
遞迴結果

方式二 promise

function p(time) {
   return new Promise((resolve, reject) => {
       //模仿ajax請求
       setTimeout(() => {
           resolve(time);
       }, time);
   });
}

(async function foo() {
   let arr = [];
   for (let i = 3000; i >= 0; i -= 1000) {
       arr.
push(await p(i)); //await會一直等待promise返回成功結果 } console.log('Promise方式結果:',arr); })()

測試結果:
promise結果

方式三 ajax async屬性

let arr = [];
for (let i = 0; i < 3; i++) {
    $.ajax({
        url: 'http://poetry.apiopen.top/getTime',
        type: 'get',
        async: false, //預設為true,ajax預設非同步執行,通過async: false變為同步方式執行即可
success(resp) { if (resp && resp.result) { arr.push(i+" "+resp.result.dateTime); } } }); } console.log("async方式結果:", arr);

測試結果:
ajax async結果