jQuery嵌套ajax forEach等待异步

问题描述

我有一个数组,我想遍历它并对服务器进行 ajax 调用。等待另一个数组的响应,而不是结果,我必须遍历结果并进行 ajax 调用。只有这样,我才能转向外部承诺。

注意我使用首字母缩略词 promise 只是因为我尝试了 promise 并且没有任何运气。

所以基本上我想实现这个序列:

输出1->输入1->输入2->输入3->输出2

...等等 基本上所有的请求都是 1 x 1,当一个外部完成时,内部开始 1 x 1 比准备好时处理下一个外部等等。

代码如下:

var OuterPromises = range(1,10);
var InnerPromises = [];

$('.--btn-start-promising').click(function() {
    asyncForEach(OuterPromises,async (OuterPromise) => {
        await $.ajax({
            url: '/index.PHP/merger/outerpromise',complete: async function (_r)
            {
                try{
                    _r = JSON.parse(_r.responseText);
                    SysOut(_r);
                    asyncForEach(_r,async  (InnerPromise) => {

                        await $.ajax({
                            url: '/index.PHP/merger/innerpromise/'+InnerPromise,complete: await function(_r)
                            {
                                SysOut(_r.responseText);
                            }
                        })
                    }).catch(e => {})
                } catch (e) {
                    SysOut(e);
                }
            }
        })
    }).catch(e => {})
})

function range(min,max){
    const arr = Array(max - min + 1)
        .fill(0)
        .map((_,i) => i + min);
    return arr;
}

function SysOut(...args)
{
    $.each(args,function(i,a) {
        console.log(a);
    })
}

async function asyncForEach(array,callback) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index],index,array);
    }
}

所有调用都在完成,但它们并没有按照我想要的顺序完成,基本上它们被打乱了,有时我也会看到并行调用

我做错了什么?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)