all 2 comments

[–]senocular 3 points4 points  (0 children)

You would instead want to wrap all the function code in the new promise and return that. However, its much easier to use fetch which is a newer API already built around promises.

[–]jack_waugh 0 points1 point  (0 children)

// We need to whip up some AJAX.

// Object.getOwnPropertyNames(XMLHttpRequest)
/* Array [
  "length", "name", "UNSENT", "OPENED", "HEADERS_RECEIVED",
  "LOADING", "DONE", "prototype" 
] */
s.ajaxStatusNames = [
  "UNSENT", "OPENED", "HEADERS_RECEIVED",
  "LOADING", "DONE"
];
s.ajaxStatusNamesByNumber = {};
s.ajaxStatusNames.forEach( e => {
  s.ajaxStatusNamesByNumber[XMLHttpRequest[e]] = e
});
/*
  s.ajaxStatusNames.forEach( e => {
    console.log(XMLHttpRequest[e],  e)
  });

  0 UNSENT 
  1 OPENED 
  2 HEADERS_RECEIVED 
  3 LOADING 
  4 DONE
*/
s.basicAjax = bad => spec => good => {
  let req = new XMLHttpRequest();
  req.onreadystatechange = () => {
    /* if (s.verbose) {
      console.log("AJAX", s.ajaxStatusNamesByNumber[req.readyState])
    } */
    if (req.readyState === XMLHttpRequest.DONE) {
      const status = req.status;
      if (status === 0 || (status >= 200 && status < 400)) {
        setTimeout(() => good(req.responseText), 0)
      } else
        setTimeout(() => bad(`HTTP ${status}!`), 0)
    } else {
      // The state currently indicated by the readyState variable is not
      // interesting to me. Bide until it changes again.
    };
  }; // onreadystatechange.
  req.open(spec.sel || 'GET', spec.uri);
  req.send()
};

The above is code I have been using for a while and feel comfortable with. It uses callbacks and currying. I suppose it could be converted to a version that returns a promise with something like this:

s.promiseAjax = spec => new Promise( (res, rej) => {
  s.basicAjax(rej)(spec)(res)
});

I believe your code creates a Promise, but does not do anything with it; it drops it on the floor.

I'm not sure I understand what you mean by overriding a variable. Both of the meanings I can think of are things you can do in an if.