首页 > 解决方案 > 向服务器发送信息时遇到问题

问题描述

我的信息是从 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);
        });
    }

如何在发送数据时产生延迟,并一一发送到服务器?

标签: javascriptreact-native

解决方案


API 调用是异步调用。您可以使用promiseAsync 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);
}

推荐阅读