Home > Net >  Function does not return value when use promise, JavaScript
Function does not return value when use promise, JavaScript

Time:12-22

I have a very few knowledge in JavaScript, so sorry in advance for this question.

I have a method:

function userAgent() {
  var result = "";

  navigator.userAgentData
    .getHighEntropyValues(["platformVersion"])
    .then((ua) => {
      if (navigator.userAgentData.platform === "Windows") {
        const majorPlatformVersion = parseInt(ua.platformVersion.split(".")[0]);
        if (majorPlatformVersion >= 13) {
          console.log("Windows 11 or later");
          result = "Windows 11 or later";
        } else if (majorPlatformVersion > 0) {
          console.log("Windows 10");
          result = "Windows 10";
        } else {
          console.log("Before Windows 10");
          result = "Before Windows 10";
        }
      } else {
        console.log("Not running on Windows");
        result = "Not running on Windows";
      }
    });

  return result;
}

And it returns empty string, but prints to console the correct value.

Please, tell me what is my mistake and how to return value here, I want to use it after.

Thank you!

CodePudding user response:

You need to do two things. First return the promise with:

return navigator.userAgentData.getHighEntropyValues(["platformVersion"]).then(...).

Then, return the desired value from within the .then() handler. The first return above will return the promise from your function. The return inside the .then() handler will make that value become the resolved value of the promise you're returning.

function userAgent() {
    return navigator.userAgentData.getHighEntropyValues(["platformVersion"]).then(ua => {
        if (navigator.userAgentData.platform === "Windows") {
            const majorPlatformVersion = parseInt(ua.platformVersion.split('.')[0]);
            if (majorPlatformVersion >= 13) {
                console.log("Windows 11 or later");
                return "Windows 11 or later";
            } else if (majorPlatformVersion > 0) {
                console.log("Windows 10");
                return "Windows 10";
            } else {
                console.log("Before Windows 10");
                return "Before Windows 10";
            }
        } else {
            console.log("Not running on Windows");
            return "Not running on Windows";
        }
    });
}

Then, you would call that like this:

userAgent().then(result => {
   // use the result here
   console.log(result);
}); 
  • Related