get result of promise

2

I want to get the result of the promise but I can not, is it possible?

function initPromise() {
  return new Promise(function(res,rej) {
    res("uno");
  })
}

let data=initPromise().then(function(result) {
    console.log(result); 
    return "dos";
})
console.log(data);//quiero obtener la cadena "dos"
    
asked by hubman 02.08.2018 в 17:43
source

2 answers

2

Your example is not very good because the promise returns "one" in hard. And you want to get "two".

Suppose you can pass a parameter to initPromise

function initPromise(numero) {
  return new Promise(function(res,rej) {
    res(numero);
  })
}

let data=initPromise("dos").then(function(result) {
    console.log(result); // imprime "dos";
    return result;
});

As data is a promise, if the logueas is not going to print the value with which the promise is resolved. It will print Promise {<pending>} (although in this case it prints an empty object ... probably things from the sn snippets).

If what you want is to obtain the value of the answer in a synchronous way (outside the then). This can only be done using async / await:

async function initPromise(numero) {
  return new Promise(function(res, rej) {
    res(numero);
  })
}

async function obtenerValor() {
  let data = await initPromise("dos");

  console.log(data);
}

obtenerValor();

The problem is that to use await you have to be inside a function async that in the example is obtenerValor .

You will have to use a transpiler (e.g. Babel) for that to work in a browser.

Addendum:

Since initPromise declared as async always returns a promise, it does not make sense to return a promise new Promise() from it. In the same way, if the value returned is in itself a promise, it does not make sense to declare the function as async. In other words:

// devuelve una promesa
function retornaPromesa() {
   return new Promise(...);
}

// también devuelve una promesa
async function retornaValor() {
   return 1;
}

// esto es redundante
async function retornaValorDePromesa() {
   return new Promise(...);
}

Now, in what case would the redundant example make sense?

The grace of declaring the function as async is that within it we can use await . For example, to request a user's permissions to an API:

// queremos hacer algo con permisos antes de retornarlos
async function revisaPermisos() {
   try {
     let permisos = await axios.get('/permisos/123');
     if(!permisos.usuario) {
       throw new Error('No es usuario');
     } else if (!permisos.activo) {
       throw new Error('Es usuario pero no está activo');
     }
     return permisos;
   } catch (err) {
     throw err;
   }
}

In this example, I want to handle the answer in the function instead of passing that job to the caller (since they can call it from many places). If the request to the API throws an error, and revisaPermisos is called using revisaPermisos().then(...).catch(...) the error will appear in the block catch . But if the call to the API does not throw error ... and nevertheless the answer must fulfill certain conditions, I can parsear that answer and submit it to certain validations, throwing errors customized by me when they are not fulfilled .

This may not be the case given the OP question, but it is an example of when it would make sense to declare async a function that inside will call another function that returns a promise.

    
answered by 03.08.2018 в 15:27
0

I would recommend you reformulate your code as follows

var opera = new Promise(function(res, rej){
  var numero = "uno"
  res(numero)
})


let data = function(){
  opera.then(function(val){
    console.log(val)
  })
console.log("dos")
}

data()

I'll explain:

  • Assign the promise to a variable, so that we can access it later, by the name of said variable
  • The message of "two" assign it to a variable that will only be returned when the promise is resolved correctly
  • to access the functionality of the promise, I declare a variable called data that will execute an anonymous function and this in turn will allow me to access the promise and its states
  • As the promise is waiting to receive a value, step in the first then of the promise a variable called val which will take the value of "two", which is declared in the variable number, the promise it will run first then the message "two appears first"; later I only send to print in console.log() the message "one"
  • To activate the functionality of the code, I invoke the function at the end of my code in this way data()
  •   

    If you place the console.log() out of reach of then() it goes to   print first the message that says dos because this same should not   wait for the promise to be resolved and for this very reason it is going to   print the message uno just after

        
    answered by 02.08.2018 в 18:11