M
M
Maxim Belousov2021-07-05 20:41:22
JavaScript
Maxim Belousov, 2021-07-05 20:41:22

Why does alert called with no arguments show the result?

Hello!

There is a promise with a .then handler that displays a dialog box with a fulfilled result:

let promise = new Promise(resolve => resolve('Done!')).then(result => alert(result)) // Done!

The .then method takes an arrow function as an argument. In the arrow function as an argument, in turn, we pass result - the value with which the promise was successfully completed.

And now let's slightly change the code in the part of the .then method:

let promise = new Promise(resolve => resolve('Done!')).then(alert) // Done!

Now we only passed the alert function to the .then method, but in both cases we get the same result - the display of a dialog box with the message “Done!”.

Why, in the second case, in the .then method, without passing the argument in the form of result to alert, did we still get its output? Does the .then method implicitly pass that argument to the function somehow? Or how does this magic work?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Neverov, 2021-07-05
@dedavarera

You pass a function to then anyway.
In the first case, this function:
result => alert(result)
In the second, it's simple: It's
alert
easier to get on the variables, it seems to me. If you pass the function from the first example to a variable and feed then, everything will work exactly the same:

const func = result => alert(result);
let promise = new Promise(resolve => resolve('Done!')).then(func) //Выполнится func

The point is that in all three cases you pass as an argument to then a function that takes 1 argument (result) and does something with it: passes it to alert or displays a dialog box right away, there is no difference.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question