javascript - 向服务器发送信息时遇到问题
问题描述
我的信息是从 sqlite 读取的,并为每条信息创建一个 json,这些 json 被发送到服务器。
问题是,使用更多的 Json,它不起作用,并且在服务器端,它遇到错误 json is a sent at time and they get the same id on the server。
我一个一个发的时候没有这个问题,但是当两个个数上去的时候发现这个问题
我的代码:
db.transaction((tx) => {
tx.executeSql(
"SELECT * FROM VoucherTable INNER JOIN VoucherItemsTable ON VoucherItemsTable.VoucherId = VoucherTable.VoucherId",
[],
(tx, res) => {
let rows = res.rows.length;
if (rows > 0) {
let VoucherTable = [];
for (let i = 0; i < rows; i++) {
VoucherTable.push(res.rows.item(i));
}
this.setState({ VoucherTable: VoucherTable, VoucherTableLength: VoucherTable.length });
let localVoucherId = -1;
let voucherItemsData = "";
let voucherData = "";
let voucherItemCount = 0;
VoucherTable.forEach((key, index) => {
if (localVoucherId !== key.VoucherId && voucherData !== "") {
this.sendData(voucherData, voucherItemsData);
//reset variables
voucherData = "";
voucherItemsData = "";
voucherItemCount = 0;
}
localVoucherId = key.VoucherId;
if (voucherItemCount === 0) {
if (voucherData === "")
voucherData = '"VoucherId":' + key.VoucherId + ',"CreationTime":"' + Moment(key.CreationTime, 'jYYYY-jM-jD').format('YYYY-MM-DD') + '","Description":"' + key.Description + '"';
if (voucherItemsData !== "")
voucherItemsData += ",";
voucherItemsData += '{"Credit":' + key.Credit + ',"ItemDlRef":"' + key.ItemDlRef + '","ItemAccountSlRef":"' + key.ItemAccountSlRef + '","Description":"' + key.Description + '","CurrencyRef":' + key.CurrencyRef + ',"CurrencyRate":' + key.CurrencyRate + ',"CurrencyDebit":"' + key.CurrencyDebit + '","CurrencyCredit":"' + key.CurrencyCredit + '"}';
voucherItemCount++;
} else {
voucherItemsData += ",";
voucherItemsData += '{"Debit":' + key.Debit + ',"ItemDlRef":"' + key.ItemDlRef + '","ItemAccountSlRef":"' + key.ItemAccountSlRef + '","Description":"' + key.Description + '","CurrencyRef":' + key.CurrencyRef + ',"CurrencyRate":' + key.CurrencyRate + ',"CurrencyDebit":"' + key.CurrencyDebit + '","CurrencyCredit":"' + key.CurrencyCredit + '"}';
}
})
this.sendData(voucherData, voucherItemsData);
} else {
this.setState({ loading: false });
this.autoClose('No data for sync!', 'Error', 3000);
}
},
(err) => { console.log(err) }
)
});
sendData = (voucherData, voucherItemData) => {
const data = '{' + voucherData + ',"Items":[' + voucherItemData + ']}';
let VoucherJson = JSON.parse(data);
//fetch
let sycnAddress = this.state.syncAddress;
var myHeaders = new Headers();
myHeaders.append("token", this.state.Token);
myHeaders.append("Content-Type", "application/json");
let Data = data;
var requestOptions = {
method: 'POST',
headers: myHeaders,
body: Data,
redirect: 'follow'
};
fetch(sycnAddress + "SetVoucher", requestOptions)
.then(response => response.json())
.then((responseJson) => {
if (responseJson.status === 1) {
this.setState({ loading: false });
this.autoClose('Sync Successfuly.', 'success', 3000);
}
return responseJson;
})
.catch((error) => {
console.log('error' + error);
});
}
如何在发送数据时产生延迟,并一一发送到服务器?
解决方案
API 调用是异步调用。您可以使用promise或Async await。
承诺
fetch('/article/promise-chaining/user.json')
.then(user => fetch(`https://api.github.com/users/${user.name}`))
.then(response => response.json())
.then(githubUser => new Promise(function(resolve, reject) {
let img = document.createElement('img');
img.src = githubUser.avatar_url;
img.className = "promise-avatar-example";
document.body.append(img);
setTimeout(() => {
img.remove();
resolve(githubUser);
}, 3000);
}))
// triggers after 3 seconds
.then(githubUser => alert(`Finished showing ${githubUser.name}`));
异步等待
function async doSomeCrazyThingWithAPI(){
let user = await fetch('/article/promise-chaining/user.json');
let response = await fetch('https://api.github.com/users/${user.name}');
let githubUser = await appendImageAndThenRemove(10);
// Will wait for 10 seconds here
alert(githubUser);
}
推荐阅读
- c# - sqlite sqlitecommand ExecuteNonQuery vs ExecuteNonQueryAsync c#
- r - 用插值替换行之前的值小于行的值
- python - 如何在python中找到以特定字母集开头的单词的字符串?
- django - Request.Post 方法在 Django 中无法正常工作
- angular - 如何使用 viewcontainerref 生成新组件?
- javascript - 崩溃后立即在反应引导中崩溃
- c# - 我们可以在实际项目中使用工厂模式的场景
- security - 尝试在安全的 spark-java 应用程序中连接到 localhost:4567 时出现奇怪的响应
- svg - svg 转换元素在 Edge 中不起作用
- javascript - 在 render() 中没有回调 React 函数