How do I return a value from a promise in Javascript?

Good I'm facing the following problem, I'm contributing on a mozilla extension, but most browser APIs use promises to get things done, only the problem is that I don't dominate much. So I would 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");
    }
});

Note: one detail I noticed is that the way the code is promise can't handle functions that use return, if it wasn't for that it would have finished now.

Author: Marcelo Batista, 2018-05-07

2 answers

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

Https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Promise

The" returns " of Promises are always accessed by the function .then () that works as a "try"or .catch() which functions as a"catch". In .then() the return is equivalent to the value passed to the resolve () function when creating a Promise or the return of the latter .then (), already the .catch () which serves for error handling receives only the err parameter of type Error which consists of an Exception with the error data.

Already ES2015 onwards it is possible to work with async/ await, I recommend that you read: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/funcoes_assincronas

With this it is possible to return the value of a Promise and assign it to a variavel. Ex.:

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

    let result = await promise;
}
 1
Author: Vinicius Guedes, 2018-05-07 16:46:28

Simple example of promise .

var promise = new Promise( (resolve, reject) => {
    let idade = 18

    if (idade >= 18) {
        resolve('Maior de idade.');
    } else {
        reject('Menor de idade.');
    }
});

promise.then( resultado => {
    console.log(resultado); //Maior de idade.
}, erro => {
    console.log(erro); //Menor de idade.
});
 1
Author: acacio.martins, 2019-07-03 21:34:23