return value of a promise in javascript

-1

Well I'm facing the following problem, I'm contributing in a mozilla extension but most of the browser apis use promises to do things, but the problem is that I do not master much. Well I'd really like to know how to return the value of a promise to a variable.

a = function() {
  var promise = new Promise(function(resolve, reject) {
    resolve(browser.storage.local.get().then(function(v) {
      ClockFormat=v.formClock;//aqui estou pegando um item do objeto da api
    }));
  });

  return promise;
};
a().then(function(result) {
    if(ClockFormat=="12"){
      console.log("12 horas");
    }else{
      console.log("24 horas");
    }
});

    
asked by anonymous 07.05.2018 / 04:22

1 answer

0

Promises are asynchronous, have you ever studied asynchronous languages before? If I do not recommend reading:

link

The "returns" of Promises are always accessed by the .then () function that works like a "try" or .catch () that works like a "catch". No .then () returns the value passed to the function resolves () when creating a Promise or the return of the last .then (), whereas the .catch () that serves for error handling only receives the err parameter of type Error that consists of an Exception with the error data.

Since the ES2015 onwards it is possible to work with async / await, I recommend that you read:

With this you can return the value of a Promise and assign it to a variable. Ex.:

const someFunction = async () => 
{
    let promise = new Promise((resolve, reject) => resolve(2));

    let result = await promise;
}
    
07.05.2018 / 18:46