Открывайте несколько jQuery подтверждений после завершения обработки одного - PullRequest
0 голосов
/ 17 марта 2020

У меня есть вызов API, где я получаю массив в ответ. Теперь я хочу открыть jQuery Подтвердить , зацикливая ответ по очереди, но проблема в том, что они открываются все сразу. Вот код

axios.post('/orders/ask-for-order-price', {ids: order_ids}).then((response) => {
        if (response.status === 200) {
            let orders = response.data
            $.each(orders, function (index, item) {
                if (item.ask_for_price === true) {
                    showPricePopup(index, item.address, item.order_type, item.client_name)
                }
            })
        }
    }).catch((error) => {
        console.info(error)
    })



showPricePopup = (id, address, type, client_name) => {
    $.confirm({
        title: 'Please enter order price for ',
        content: '' +
            '<form action="" class="formName">' +
            '<div class="form-group">' +
            '<label><strong>' + type + '</strong> at <strong>' + address + '</strong> by <strong>' + client_name + '</strong></label>' +
            '<input type="text" placeholder="Enter the price here" class="price form-control" required />' +
            '</div>' +
            '</form>',
        buttons: {
            formSubmit: {
                text: 'Submit',
                btnClass: 'btn-blue',
                action: function () {
                    var price = this.$content.find('.price').val();
                    if (!price) {
                        $.alert('provide a valid price');
                        return false;
                    }
                    $.alert('Your price is ' + price);
                }
            },
            cancel: function () {
                //close
            },
        },
        onContentReady: function () {
            // bind to events
            var jc = this;
            this.$content.find('form').on('submit', function (e) {
                // if the user submits the form by pressing enter in the field.
                e.preventDefault();
                jc.$$formSubmit.trigger('click'); // reference the button and click it
            });
        }
    });

}

РЕДАКТИРОВАТЬ response.data выглядит так

{
  "1": {
    "ask_for_price": true,
    "order_type": "Construction New",
    "address": "3685  Simons Hollow Road, Hanover Township, PA",
    "created_at": "03/16/20",
    "client_name": "Muhammad Ahmad Baig",

  },
  "2": {
    "ask_for_price": true,
    "order_type": "Phase I",
    "address": "4744  Horizon Circle, University Place, WA",
    "created_at": "03/16/20",
    "client_name": "Muhammad Ahmad Baig",

  },
  "3": {
    "ask_for_price": true,
    "order_type": "ETS",
    "address": "1491  Gambler Lane, ALLENDALE, IL",
    "created_at": "03/16/20",
    "client_name": "Muhammad Ahmad Baig",

  },
  "4": {
    "ask_for_price": true,
    "order_type": "Property Condition Assesment",
    "address": "58  Glenview Drive, Corpus Christi, TX",
    "created_at": "03/16/20",
    "client_name": "Muhammad Ahmad Baig",

  },
  "5": {
    "ask_for_price": true,
    "order_type": "Property Condition Assesment (Short Form)",
    "address": "858  Duncan Avenue, Scarsdale, NY",
    "created_at": "03/16/20",
    "client_name": "Muhammad Ahmad Baig",

  },
  "6": {
    "ask_for_price": true,
    "order_type": "Plan and Cost Review",
    "address": "3116  Wolf Pen Road, Pacifica, CA",
    "created_at": "03/16/20",
    "client_name": "Muhammad Ahmad Baig",

  },
}

1 Ответ

0 голосов
/ 17 марта 2020

Если вы хотите, чтобы всплывающие окна отображались последовательно, вам нужно будет использовать for l oop в сочетании с обещаниями. Причина в том, что вы хотите дождаться закрытия одного всплывающего окна (которое разрешит обещание), прежде чем переходить к следующему:

for (const key of Object.keys(orders)) {
    const item = orders[key];

    // We show popup sequentially, and wait for it to be resolved before moving on to the next
    await showPricePopup(index, item.address, item.order_type, item.client_name);
}

ПРИМЕЧАНИЕ: Для этого работать, убедитесь, что обратный вызов в вашей .then() является async функцией, т.е. .then(async (response) => { ... }).

Это подводит нас к следующему шагу: showPricePopup должен возвращать обещание: вы можете просто заключить в оболочку все ваше внутреннее содержание функции как таковое:

showPricePopup = (id, address, type, client_name) => {
    return new Promise(resolve => {
        // Original logic inside the function
    });
}

Затем убедитесь, что вы выполняете обещание всякий раз, когда (1) форма успешно отправлена ​​или (2) форма отклонена. Выполнение обещания приведет к тому, что await в for l oop станет равным sh, что позволит нам перейти к открытию модального для следующего элемента в следующей итерации.

Поэтому , ваш обновленный код должен выглядеть примерно так:

axios.post('/orders/ask-for-order-price', {
    ids: order_ids
}).then(async (response) => {
    if (response.status === 200) {
        let orders = response.data;

        // Use for loop to iterate through all orders
        // In each iteration, await promise returned by `showPricePopup()`
        for (const key of Object.keys(orders)) {
            const item = orders[key];
            await showPricePopup(index, item.address, item.order_type, item.client_name);
        }
    }
}).catch((error) => {
    console.info(error)
})

showPricePopup = (id, address, type, client_name) => {
    return new Promise((resolve) => {
        $.confirm({
            title: 'Please enter order price for ',
            content: '' +
                '<form action="" class="formName">' +
                '<div class="form-group">' +
                '<label><strong>' + type + '</strong> at <strong>' + address + '</strong> by <strong>' + client_name + '</strong></label>' +
                '<input type="text" placeholder="Enter the price here" class="price form-control" required />' +
                '</div>' +
                '</form>',
            buttons: {
                formSubmit: {
                    text: 'Submit',
                    btnClass: 'btn-blue',
                    action: function () {
                        var price = this.$content.find('.price').val();
                        if (!price) {
                            $.alert('provide a valid price');
                            return false;
                        }
                        $.alert('Your price is ' + price);

                        // Resolve your promise here so you can move on to the next one
                        resolve();
                    }
                },
                cancel: function () {
                    // If the modal is closed, you also want to resolve the promise
                    resolve();
                },
            },
            onContentReady: function () {
                // bind to events
                var jc = this;
                this.$content.find('form').on('submit', function (e) {
                    // if the user submits the form by pressing enter in the field.
                    e.preventDefault();
                    jc.$$formSubmit.trigger('click'); // reference the button and click it
                });
            }
        });
    });
}
...