簡體   English   中英

在 foreach 中的 Ajax 中設置超時

[英]setTimeout inside a Ajax in a foreach

我試圖在 1 秒后調用一個函數,但是這個函數是在 foreach 中的 ajax 中調用的。

代碼:

let index = 1;
portais.forEach(portal => {
    setTimeout(() => {
        $.ajax({
            type: "POST",
            url: url,
            async: false,
            success: function (data) {
                index++;
                text(index, total); // I want to call this function, after 1 second
            }
        });
    }, 1000);
});

但只在第一次和最后一次打電話。

我已經嘗試將此函數放在異步函數中並使用承諾來解決,但仍然無效。 這是我嘗試的其他代碼:

let index = 1;
const delay = (amount = number) => {
    return new Promise((resolve) => {
        setTimeout(resolve, amount);
    });
}

async function forPortais(){
    for(index; index<=total; index++){
        $.ajax({
            type: "POST",
            url: `/exportacao/${portais[index].arquivo}.php`,
            async: false,
            success: async function (data) {
                if(index>total){
                    text(index, total);
                    await delay(1000);

            }
        });
    }
}
forPortais();
  • 如何在 1 秒后調用此函數text()

預期的結果是該函數被調用 7 次,超時為 1 秒。

我可以通過創建異步 foreach 和異步延遲來解決這個問題。

編碼:

const waitFor = (ms) => new Promise(r => setTimeout(r, ms))

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

    const start = async () => {
        await asyncForEach(portais, async (portal) => {
            await waitFor(100);
            text(index, total);
            index++;
            $.ajax({
                type: "POST",
                url: url,
                async: false,
            });
        })
    }
    start();

有了這個功能,你可以做你想做的事,但對你的瀏覽器來說會很貴

function sleep(milliseconds) {
    var start = new Date().getTime();
    while(true){
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}

let index = 1;
portais.forEach(portal => {
    $.ajax({
        type: "POST",
        url: url,
        async: false,
        success: function (data) {
            index++;
            sleep(1000);
            text(index, total);
        }
    });
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM