Search code examples
javascriptasynchronousasync-awaitxmlhttprequesttampermonkey

Function not able to call value from XHTML request result in another function, logging undefined (tampermonkey)


Problem is the bottom function not able to pull the result of the xmlhttprequest. Confused on how i would add a promise for this

Do i have to use aysnc and await, or how would i be able to get the result of the function after the request?

I have tested calling the degreesInner console logging within the weatherPull function and it returns the right value. It looks like the kaminoan function doesnt wait for the weatherPull function to finish the request and logs undefined


Solution

  • Simply wrap the return result within a promise and use the promise resolve and reject function in order to return the result or error:

     function weatherPull () {
      return new Promise((resolve, reject) => GM_xmlhttpRequest({
        method: 'GET',
        url: 'https://weather.com/weather/today/l/97a4d5b4ba6364679573ce81d1f6ae73791fab877b50c3433657376f8b676c27',
        onload: function (pull) {
          const fetch = new DOMParser();
          const html = fetch.parseFromString(pull.responseText, 'text/html');
          const degree = html.querySelector('#WxuCurrentConditions-main-eb4b02cb-917b-45ec-97ec-d4eb947f6b6a > div > section > div > div.CurrentConditions--body--l_4-Z > div.CurrentConditions--columns--30npQ > div.CurrentConditions--primary--2DOqs > span');
          resolve(degree.innerHTML);
        },
        onerror: reject
      }));
    }
    

    You could then access the data with the promise "then" function, or if a error is thrown, catch it with the promise catch function:

    function kaminoan () {
      weatherPull()
        .then((data) => console.log('this is your data', data))
        .catch((error) => console.log('failed to fetch data', error));
    }
    

    If you would like to do it the async await way, following approach is equivalent:

    async function kaminoan () {
      try {
        const data = await weatherPull();
        console.log('this is your data', data);
      } catch (error) {
        console.log('failed to fetch data', error);
      }
    }