У меня есть цикл 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)...
:
: