簡體   English   中英

向服務器發送信息時遇到問題

[英]Having trouble sending information to the server

我的信息是從 sqlite 和為每條信息創建的 json 讀取的,這些 json 被發送到服務器。

問題是使用更多的 Json,它不起作用,並且在服務器端,它遇到錯誤 json 一次發送,它們在服務器上獲得相同的 id。

我一個一個發的時候沒有這個問題,但是當兩個個數上去的時候發現這個問題

我的代碼:

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 調用是異步調用。 您可以使用promiseAsync await

promise

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM