Promise return

Asked

Viewed 421 times

2

Considering the example below:

function retornaValor (){
  return promiseQueveioDeAlgumaLib.then(
    function(oQueQueroRetornar){
      return {
        sucesso: true,
        data : oQueQueroRetornar
      }
    },
    function(opsAlgoErrado){
      return {
        sucesso : false,
        data : opsAlgoErrado
      }
    }
  )
}

console.log(retornaValor())

What must I do to make sure I actually have oQueQueroRetornar or opsAlgoErrado and not a pending Promise?

For the record, when I write a code that way inside Meteor.methods it works exactly as I would like, IE, returns a value I return to the customer but out of methods or in the client (browser, using or not any framework) I have is a pending Promise.

  • You simply cannot return from an asynchronous operation. I mean, asynchronous functions even return, but to no one.

  • 2

    I think you’re trying to avoid an asynchronous flow and you’re looking for a way to do synchronous is that it? In that case I think you really have to accept that some things are asynchronous... if that doesn’t explain the question more clearly.

  • Yes, I need it synchronous, the problem is that 101% of Npm libraries are asynchronous, which makes me hostage to Meteor/nodejs + Fibers/Future, which allow me to control that.

  • You can pass a function of callback as a parameter of retornaValor, and instead of returning to make a callback({sucesso: true, data: oQueQueroRetornar});, on the other side you would do so: retornaValor(function(response) { console.log(response); });

  • Yes I can, but I wouldn’t, since my need is to returnValue() actually return a value

1 answer

1


To return the value of the file you need to make your operation synchronous, so that the log waits for the file to be resolved and then prints the returned value. This can be done using the await function:

// Testando com uma promise qualquer.
let promiseQueveioDeAlgumaLib =         
fetch('https://jsonplaceholder.typicode.com/users/1').then(res => res.json());

function retornaValor() {
  return promiseQueveioDeAlgumaLib.then(
    function(oQueQueroRetornar) {
      return {
        sucesso: true,
        data : oQueQueroRetornar
      }
    },
    function(opsAlgoErrado) {
      return {
       sucesso : false,
       data : opsAlgoErrado
      }
    }
  );
}

console.log(await retornaValor());

await forces a synchronous behavior in the operation, it will ensure that the Promise has resolved before returning its value.

To learn more about Predomises and this asynchronous behavior, as well as good practices, I recommend reading of that post.

Browser other questions tagged

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