0

I want to create a file of functions to be used in other files:

location.js file:

function state() {
  navigator.permissions.query({ name: "geolocation" }).then((pos) => {
    return pos.state;
  });
}

function ask() {
  navigator.geolocation.getCurrentPosition((pos) => {
    return pos.coords;
  }, (err) => {
    return err;
  });
}

functions... 

export {state, ask};

another file:

import * as location from "location.js"

console.log(location.state());
console.log(location.ask());

how to return pos.state in the first function (return the result, not the promise) and the pos.coords in the second one?

Adam
  • 89
  • 1
  • 9
  • You can't return `pos.state` directly as it's only available when the promise resolves, which occurs after your `state` function has already returned. You need to return the promise – Nick Parsons Mar 25 '22 at 07:59
  • @NickParsons what about the second one – Adam Mar 25 '22 at 08:05
  • That has the same issue as the first. Although, `getCurrentPosition()` doesn't return a Promise like `query()` does. If you want you can make `ask` return a Promise that resolves with `pos.coords`, you can follow this answer for that: [How do I convert an existing callback API to promises?](https://stackoverflow.com/a/22519785). Once you have your functins returning promises, you can use `location.state().then(state => console.log(state)` and the same idea for `.ask()` – Nick Parsons Mar 25 '22 at 09:01

0 Answers0