简体   繁体   English

跳出 Promises 的 for 循环

[英]Break out of for loop of Promises

I come to you with a question related to for loops and promises.我带着一个与 for 循环和 Promise 相关的问题来找你。

So to explain the situation: I have a for loop that will run a number of times.所以解释一下情况:我有一个for循环,它会运行很多次。 This loop uses fetch to post to an API.此循环使用fetch发布到 API。 Depending on what comes back as a response from each POST request, I want to break the loop if a certain condition is met.根据每个 POST 请求的响应返回的内容,如果满足某个条件,我想打破循环。

So for example, if the loop is set to run 5 times but on the 3rd iteration the break condition is met, I do not want to execute the rest of it, therefore preventing the other POST requests from executing.因此,例如,如果循环设置为运行 5 次,但在第 3 次迭代时满足中断条件,我不想执行它的 rest,从而阻止其他 POST 请求执行。

I think you will understand the issue once you see the code:我想一旦你看到代码你就会明白这个问题:

send: function () {
    const procedure = 'someProcedure';
    const fields = document.querySelectorAll('.field');
    for(let i = 0; i < fields.length; i++) {
        const obj = {
            procedure: procedure,
            saunaScheduleId: fields[i].dataset.id,
            guestMediumHID: '',
            guestMediumNumber: fields[i].innerHTML
        };
        fetch(EventBooking.variables.api, {
            method: "POST",
            mode: 'cors',
            redirect: 'follow',
            headers: new Headers({ 'Content-Type': 'application/json; charset=utf-8' }),
            body: JSON.stringify(obj)
        })
        .then(response => response.json())
        .then(data => {
            if (data[0].resultCode == 3) {
                console.log(obj.guestMediumNumber + ' booked this event.');
                return;
            }
            else if(data[0].resultCode == 0 && i == fields.length - 1) {
                console.log('Booking completed successfully!');
                EventBooking.booking.clear();
            }
        });
    }
}

From what I read, It has to do with the for loop somehow being done way ahead of the API calls.从我读到的内容来看,这与在 API 调用之前以某种方式完成的for循环有关。 The second if in the loop seems to be doing good once all the calls have been executed successfully it shows one message for all of them.一旦所有调用都成功执行,循环中的第二个 if 似乎做得很好,它会为所有调用显示一条消息。

How would you go about handling this kind of situation?你会如何处理这种情况?

Thank you for your help.谢谢您的帮助。 Cheers!干杯!

Use recursive使用递归

send: function () {
    const procedure = 'someProcedure';
    const fields = document.querySelectorAll('.field');
    const fetching = index => {
        if (index >= fields.length) return;
        const obj = {
            procedure: procedure,
            saunaScheduleId: fields[index].dataset.id,
            guestMediumHID: '',
            guestMediumNumber: fields[index].innerHTML
        };
        fetch(EventBooking.variables.api, {
            method: "POST",
            mode: 'cors',
            redirect: 'follow',
            headers: new Headers({ 'Content-Type': 'application/json; charset=utf-8' }),
            body: JSON.stringify(obj)
        })
        .then(response => response.json())
        .then(data => {
            if (data[0].resultCode == 3) {
                console.log(obj.guestMediumNumber + ' booked this event.');
                return;
            }
            else if(data[0].resultCode == 0 && index == fields.length - 1) {
                console.log('Booking completed successfully!');
                EventBooking.booking.clear();
            }
            fetching(index + 1);
        });
    };
    fetching(0);
}

I have decided to go for this:为此,我决定使用 go:

Seems clean and works.看起来干净而且有效。

send: async function () {
        const procedure = 'SaveSaunaEventBooking';
        const fields = document.querySelectorAll('.field');
        for(let i = 0; i < fields.length; i++) {
            const obj = {
                procedure: procedure,
                saunaScheduleId: fields[i].dataset.id,
                guestMediumHID: '',
                guestMediumNumber: fields[i].innerHTML
            };
            let response = await fetch(EventBooking.variables.api, {
                method: "POST",
                mode: 'cors',
                redirect: 'follow',
                headers: new Headers({ 'Content-Type': 'application/json; charset=utf-8' }),
                body: JSON.stringify(obj)
            })
            let data = await response.json();
            if (data[0].resultCode == 3) {
                console.log(obj.guestMediumNumber + ' booked this event.');
                return;
            }
            else if (data[0].resultCode == 0 && i == fields.length - 1) {
                console.log('Booking completed successfully!');
                EventBooking.booking.clear();
            }

        }

Thanks for all your ideas and help: :)感谢您的所有想法和帮助::)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM