Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return from a promise then()

I have got a javascript code like this:

function justTesting() {
  promise.then(function(output) {
    return output + 1;
  });
}

var test = justTesting();

I have got always an undefined value for the var test. I think that it is because the promises are not resolved yet..there is a way to return a value from a promise?

like image 666
Priscy Avatar asked Dec 04 '15 18:12

Priscy


People also ask

How do you return a value from a promise?

Promise resolve() method: If the value is a promise then promise is returned. If the value has a “then” attached to the promise, then the returned promise will follow that “then” to till the final state. The promise fulfilled with its value will be returned.

What is promise resolve () then?

resolve() The Promise. resolve() method "resolves" a given value to a Promise . If the value is a promise, that promise is returned; if the value is a thenable, Promise. resolve() will call the then() method with two callbacks it prepared; otherwise the returned promise will be fulfilled with the value.

What does promise () method do?

The . promise() method returns a dynamically generated Promise that is resolved once all actions of a certain type bound to the collection, queued or not, have ended. By default, type is "fx" , which means the returned Promise is resolved when all animations of the selected elements have completed.

What happens when you return a promise?

A value returned inside a then() handler becomes the resolution value of the promise returned from that then() . If the value returned inside the . then is a promise, the promise returned by then() will "adopt the state" of that promise and resolve/reject just as the returned promise does.


Video Answer


6 Answers

When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).

Source: https://web.dev/promises/#queuing-asynchronous-actions

like image 160
c0ming Avatar answered Sep 22 '22 12:09

c0ming


To use a promise, you have to either call a function that creates a promise or you have to create one yourself. You don't really describe what problem you're really trying to solve, but here's how you would create a promise yourself:

function justTesting(input) {
    return new Promise(function(resolve, reject) {
        // some async operation here
        setTimeout(function() {
            // resolve the promise with some value
            resolve(input + 10);
        }, 500);
    });
}

justTesting(29).then(function(val) {
   // you access the value from the promise here
   log(val);
});

// display output in snippet
function log(x) {
    document.write(x);
}

Or, if you already have a function that returns a promise, you can use that function and return its promise:

// function that returns a promise
function delay(t) {
  return new Promise(function(resolve) {
    setTimeout(function() {
      resolve();
    }, t);
  });
}

function justTesting(input) {
  return delay(100).then(function() {
    return input + 10;
  });
}

justTesting(29).then(function(val) {
  // you access the value from the promise here
  log(val);
});

// display output in snippet
function log(x) {
  document.write(x);
}
like image 25
jfriend00 Avatar answered Sep 26 '22 12:09

jfriend00


What I have done here is that I have returned a promise from the justTesting function. You can then get the result when the function is resolved.

// new answer

function justTesting() {
  return new Promise((resolve, reject) => {
    if (true) {
      return resolve("testing");
    } else {
      return reject("promise failed");
   }
 });
}

justTesting()
  .then(res => {
     let test = res;
     // do something with the output :)
  })
  .catch(err => {
    console.log(err);
  });

Hope this helps!

// old answer

function justTesting() {
  return promise.then(function(output) {
    return output + 1;
  });
}

justTesting().then((res) => {
     var test = res;
    // do something with the output :)
    }
like image 32
Vidur Singla Avatar answered Sep 23 '22 12:09

Vidur Singla


Promises don't "return" values, they pass them to a callback (which you supply with .then()).

It's probably trying to say that you're supposed to do resolve(someObject); inside the promise implementation.

Then in your then code you can reference someObject to do what you want.

like image 42
Bigeyes Avatar answered Sep 26 '22 12:09

Bigeyes


I prefer to use "await" command and async functions to get rid of confusions of promises,

In this case I would write an asynchronous function first, this will be used instead of the anonymous function called under "promise.then" part of this question :

async function SubFunction(output){

   // Call to database , returns a promise, like an Ajax call etc :

   const response = await axios.get( GetApiHost() + '/api/some_endpoint')

   // Return :
   return response;

}

and then I would call this function from main function :

async function justTesting() {
   const lv_result = await SubFunction(output);

   return lv_result + 1;
}

Noting that I returned both main function and sub function to async functions here.

like image 39
Bulent Balci Avatar answered Sep 24 '22 12:09

Bulent Balci


I think what the original poster wants is to return an unwrapped value from a promise without actually returning another promise. Unless proven otherwise, I'm afraid this is not possible outside of a then() or async/await context. You always get a promise no matter what.

like image 24
Jose Quijada Avatar answered Sep 25 '22 12:09

Jose Quijada