0

I am trying to extract value from a Promise. I am able to print the result before it gets returned in a Promise.

function countTotalInvItem() {
  var params = 'service=shopping&request=getshopitems&mode=count';
  var jsonRes = xmlHttpSend(params).then((value) => {
    if (value instanceof Promise) {
      console.log('Promise found');
    } else {
      console.log('Promise NOT');
      if (value != null) {
        console.log('Value: ' + value);
      } else {
        console.log('NULL value');
      }
    }
  });
}

async function xmlHttpSend(params) {
  let myPromise = new Promise(function (resolve) {
    var xhr = new XMLHttpRequest();
    var url = 'portal?' + params;

    xhr.onreadystatechange = function (response) {
      if (xhr.readyState == 4 && xhr.status == 200) {
        var rs = parseReturn(xhr.responseText);
        console.log('ResultSet >>> ' + rs.toString());
        if (
          rs.success === 'true' &&
          rs.resultPayloadType === 'json' &&
          rs.result !== null
        ) {
          console.log('Parsing JSON ...');
          var json = JSON.parse(rs.result);
          if (json === null) {
            console.log('NO JSON RESULT !!!');
          } else {
            console.log('JSON Result Parsed: ' + json[0].count);
          }
          resolve(json);
        } else {
          console.log('RS has ERROR !!!');
          resolve(null);
        }
      }
    };
    xhr.open('GET', url, true);
    xhr.send();
  });
}

function parseReturn(input) {
  var kvArrays1 = input.split('&');
  var service = null;
  var sessionID = null;
  var success = false;
  var errorCode = -1;
  var resultEncoding = null;
  var resultPayloadType = null;
  var result = null;

  if (kvArrays1.length > 0) {
    for (let i = 0; i < kvArrays1.length; i++) {
      if (kvArrays1[i] != null) {
        var kvArrays2 = kvArrays1[i].split('=');
        if (kvArrays2 != null) {
          switch (kvArrays2[0]) {
            case 'service':
              if (kvArrays2.length == 2) {
                service = kvArrays2[1];
              }
              break;
            case 'sessionID':
              if (kvArrays2.length == 2) {
                sessionID = kvArrays2[1];
              }
              break;
            case 'success':
              if (kvArrays2.length == 2) {
                success = kvArrays2[1];
              }
              break;
            case 'errorCode':
              if (kvArrays2.length == 2) {
                errorCode = kvArrays2[1];
              }
              break;
            case 'resultEncoding':
              if (kvArrays2.length == 2) {
                resultEncoding = kvArrays2[1];
              }
              break;
            case 'resultPayloadType':
              if (kvArrays2.length == 2) {
                resultPayloadType = kvArrays2[1];
              }
              break;
            case 'result':
              if (kvArrays2.length >= 2) {
                result = '';
                for (let j = 1; j < kvArrays2.length; j++) {
                  if (kvArrays2[j] == '') {
                    result += '=';
                  } else {
                    result = kvArrays2[j];
                  }
                }
              }
              break;
          }
        }
      }
    }
  }
  return new ResultSet(
    service,
    sessionID,
    success,
    errorCode,
    resultEncoding,
    resultPayloadType,
    result
  );
}

class ResultSet {
  constructor(
    service,
    sessionID,
    success,
    errorCode,
    resultEncoding,
    resultPayloadType,
    result
  ) {
    this.service = service;
    this.sessionID = sessionID;
    this.success = success;
    this.errorCode = errorCode;
    this.resultEncoding = resultEncoding;
    this.resultPayloadType = resultPayloadType;
    if (result != null) {
      if (result.length > 0) {
        this.result = atob(result);
      }
    }
  }

  toString() {
    return (
      'service: ' +
      this.service +
      '; sessionID: ' +
      this.sessionID +
      '; success: ' +
      this.success +
      '; errorCode: ' +
      this.errorCode +
      '; resultEncoding: ' +
      this.resultEncoding +
      '; resultPayloadType: ' +
      this.resultPayloadType +
      '; result: ' +
      this.result
    );
  }
}
 <!DOCTYPE html>
    <html>
        <head>
            <script>

            </script>
        </head>
        <body>      
            <div id="demo">
                <h2>Count Total Inventory Items</h2>
                <button type="button" onclick="countTotalInvItem()">Count</button>              
            </div>
        </body>
    </html>

The output as the screenshot shows with the developer console opened.

enter image description here

I am able to receive the response and to print out the 'count' number from the JSON that is returned.

I am missing something to pass the JSON from 'xmlHttpSend' async function to the 'countTotalInvItem' and print it as a value (which should be value of '1') ?

Thanks.

pilchard
  • 12,414
  • 5
  • 11
  • 23
thotheolh
  • 7,040
  • 7
  • 33
  • 49
  • 2
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) Where on your HTML page do you want to "print it as a value"? – Heiko Theißen Feb 11 '23 at 10:36

1 Answers1

1

I can't get that code to run properly to try to edit it, but your function xmlHttpSend does not return anything.

It declares a variable (myPromise) but does not use it. If you want this function to return a promise, you can just do:

return new Promise(function (resolve) {

instead of

let myPromise = new Promise(function (resolve) {

It is not necessary to declare xmlHttpSend as async since it returns a promise, the purpose of async is to avoid writing promises explicitly. You should also avoid using var as much as possible, it makes your code harder to understand because of the scope it gives to the variable. It is the same thing for the != and == in your functions, you should try to use !== and === as much as possible as it is easier to understand and to debug

AlanOnym
  • 131
  • 4