Как получить доступ к объекту запроса в функции fetch then / response - PullRequest
0 голосов
/ 09 февраля 2019

У меня есть цикл JavaScript итерации по массиву.Для каждого элемента я выполняю запрос на выборку для вставки объекта.Если ответ сервера указывает, что это уже вставленный объект, я пытаюсь выполнить операцию обновления с другим вызовом выборки.

Поскольку запросы асинхронные, цикл устанавливает объект запроса на следующий элемент вставки, прежде чем я пытаюсь выполнить обновлениеоперация, поэтому я в итоге запрашиваю обновление для объекта, который еще не вставлен.

Есть ли какой-нибудь способ получить доступ к объекту запроса, используемому для этой операции выборки, поэтому я могу использовать этот объект вместо цикла var?

Я пытался использовать this в методе обещания, но он возвращает ссылку на объект окна: console.log(this) ==> > Window http://localhost

Мой код:

for (var i = 0; i < expectedRows; i++) {
    var row = myArray[i];
    customerCode = row['customer_code'];
    customerName = row['customer_name'];
    customerBalance = row['customer_balance'];
    // Build body call
    var callBody = {
        user: 'USER',
        code: customerCode,
        name: customerName,
        balance: customerBalance
    };
    var fetchOptions = {
        method: "POST",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "error",
        referrer: "ux-import", 
        body: JSON.stringify(callBody),
    };
    // Call
    var epurl = baseEP + '/customer/create';
    fetch(epurl, fetchOptions)
    .then(response => response.json())
    .then(response => {
        console.log(this) // <== Window object reference
        if (response.error === 0) {
            console.log('insert ok');
            insertRows++;
        } else {
            if (response.error == 2) {
                console.log('insert error => update');
                var updateEP = baseEP + '/customer/update';
                fetch(updateEP, fetchOptions) // <== Not what you expect 
                .then(updResponse => updResponse.json())
                .then(updResponse => {
                    if (updResponse.error === 0) {
                        console.log('update ok.')
                        updateRows++;
                    } else {
                        console.log('update error: ' + updResponse.msg)
                        errorMessages.push(updResponse.msg);
                    }
                })
                .catch(error => {
                    console.log('update failure');
                    errorMessages.push(error);
                });
            } else {
                console.log('insert error.');
                errorMessages.push(response.msg);
            }
        }
    })
    .catch(error => {
        console.log('insert failure.');
        errorMessages.push(error);
    });
}

Мне нужен какой-то способ доступа к этому объекту запроса вызова для получения чего-то подобного:

var updFetchOptions = {
    method: "POST",
    cache: "no-cache",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
    redirect: "error",
    referrer: "ux-import", 
    body: this.request.body, // this as a reference to this fetch's request
}
fetch(updateEP, updFetchOptions)...
:
:

1 Ответ

0 голосов
/ 09 февраля 2019

Можете ли вы попробовать это.

for (let i = 0; i < expectedRows; i++) {
    let row = myArray[i];
    customerCode = row['customer_code'];
    customerName = row['customer_name'];
    customerBalance = row['customer_balance'];
    // Build body call
    let callBody = {
        user: 'USER',
        code: customerCode,
        name: customerName,
        balance: customerBalance
    };
    let fetchOptions = {
        method: "POST",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "error",
        referrer: "ux-import", 
        body: JSON.stringify(callBody),
    };
    // Call
    let epurl = baseEP + '/customer/create';
    fetch(epurl, fetchOptions)
    .then(response => response.json())
    .then(response => {
        console.log(this) // <== Window object reference
        if (response.error === 0) {
            console.log('insert ok');
            insertRows++;
        } else {
            if (response.error == 2) {
                console.log('insert error => update');
                let updateEP = baseEP + '/customer/update';
                fetch(updateEP, fetchOptions) // <== Not what you expect 
                .then(updResponse => updResponse.json())
                .then(updResponse => {
                    if (updResponse.error === 0) {
                        console.log('update ok.')
                        updateRows++;
                    } else {
                        console.log('update error: ' + updResponse.msg)
                        errorMessages.push(updResponse.msg);
                    }
                })
                .catch(error => {
                    console.log('update failure');
                    errorMessages.push(error);
                });
            } else {
                console.log('insert error.');
                errorMessages.push(response.msg);
            }
        }
    })
    .catch(error => {
        console.log('insert failure.');
        errorMessages.push(error);
    });
}

По сути, определение переменных с помощью var не очень хороший метод, поскольку он не поддерживает свое состояние при каждой итерации цикла.Но использование let поддерживает состояние переменной для каждой итерации, и вы можете использовать переменную даже после выполнения некоторой асинхронной задачи, такой как fetch в вашем случае.

...