【发布时间】:2019-02-09 14:59:11
【问题描述】:
我有一个遍历数组的 JavaScript 循环。对于每个项目,我执行一个获取请求以插入对象。如果服务器响应表明它是一个已经插入的对象,我会尝试使用另一个 fetch 调用进行更新操作。
由于请求是异步的,因此在我尝试更新操作之前,循环会将请求对象设置为下一个插入项,因此我最终会为尚未插入的对象请求更新。
有什么方法可以访问用于此获取操作的请求对象,以便我可以使用该对象而不是循环变量?
我尝试在 promise 方法中使用 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);
});
}
我需要一些方法来访问这个 fetch 调用请求对象来实现这样的事情:
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)...
:
:
【问题讨论】:
标签: javascript asynchronous request fetch