How do I return a Promise value in Javascript?

Asked

Viewed 3,881 times

2

Well I’m facing the following problem, I’m contributing to a Mozilla extension, but most browser Apis use Preses to do things, only the problem is that I don’t know much. So I would really like to know how to return the value of a precedent 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");
    }
});

Obs: a detail that I realized is that the way the code is the Promise can not handle functions that use Return, otherwise it would have ended already.

  • Have you tried browser.storage.local.get().then( v => {
 resolve(ClockFormat=v.formClock);
}); ?

2 answers

1

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

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

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

Promises "returns" are always accessed by the . then() function which functions as a "Try"or . catch() which functions as a "catch". No . then() the return equals the value passed to the resolve() function when creating a Promise or the return of the last . then(), already the . (catch) which serves for error handling receives only the err parameter of the Error type which consists of an Exception with the error data.

The ES2015 from now on is possible to work with async/await, I recommend you read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/funcoes_assincronas

This makes it possible to 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;
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.