0

When we have an async function that returns a variable, and then .then() is run...

What does .then() accept as parameters? Is it the variable that async returns?

For example, consider this node.js example:

const js_package = require('random_js_package');

var random_variable;


let js_function = async () => {
    random_variable = js_package();
    return random_variable;
}


js_function().then((value) => {
    for (var i=0; i<value.length; i++){
        console.log(value[i]);
    }
});

In this case, is the variable called value inside .then() what the async function returns?

In other words, is value the same as random_variable?

2
  • that's correct, yeah. Commented Aug 9, 2019 at 20:10
  • If random_variable is a value, then value will indeed be the same as random_variable. If js_package() returns Promise, then value will be whatever that Promise eventually delivers ... unless the Promises error path is taken, in which case the .then() callback won't be called at all; you need to chain .catch(errorHandler) in case that happens. Commented Aug 9, 2019 at 20:37

2 Answers 2

3

The then function accepts two arguments:

  1. a function to run if the promise is resolved
  2. a function to run if the promise is rejected

The first function you pass to it needs to accept one argument:

  1. The resolved value of a promise

Meanwhile, async functions returns:

A Promise which will be resolved with the value returned by the async function, or rejected with an uncaught exception thrown from within the async function.


So, aside from you confusing the then function with the function you pass to it: Yes.

Sign up to request clarification or add additional context in comments.

Comments

1

When you declare a function with async the function will always return a promise. So if you don't explicitly return a promise from the async function then javascript will wrap the value you return in a promise. .then() always takes a function which has a parameter which is the resolved value of a promise. So your code is correct the way it is written. In your code value will equal random_variable. Behind the scenes javascript is returning a promise from js_function which is why using .then((value) => works.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.