How to pass a parameter for a JS function inside .then, or achieve similar behavior?

javascript function parameters
how to get value from one function to another in javascript
javascript function()
how to call a function inside a function in javascript
javascript arrow function
anonymous function javascript
then javascript
how to call a function in javascript

Let's assume there is a promise createPost and a function getPosts. The first one creates a recored in a database of posts and resolves. getPosts retrieves all posts, creates a UL lists and appends it to a webpage.

 createPost ({*post contents JSON*})

When createPost is called as above, the promise waits until the posts are updated and -then- getPosts is run. However, if for some reason, I want to resolve and then run getPosts with a parameter: getPosts(param), it gets triggered right away, before promise resolves.

How (and why), can the .then callback function contain a parameter, without breaking out of the promise? Or, how can I achieve this behavior?

EDIT: Why is it, that while


does not wait for the function to resolve,

.then(() => getPosts(param));


On the root question. Say you have:

function f() {
    return 'hello';

then() takes a function as its parameter. So saying then(f) says "invoke f after the promise resolves. If you say then(f()), what you're saying is "pass the result of invoking f (which is 'hello') to then'. f gets invoked right away.

Also note, incidentally, that the function you pass to then will be invoked with a single parameter, namely the resolution of the promise to which then is attached. eg:

someAsyncFn() {
    /* return a promise that resolves to "foo!!" */

someAsyncFn().then(console.log);  // this will log foo!!

Though probably poor style, this means you can say...

createPost().then(() => param).then(getPosts);


A few more words on when function gets run...

// nothing gets invoked when we define a function
function foo() {
    return 'bar';

let a = foo;  // this doesn't invoke foo.  a is now a function

let b = foo();   // this *does* invoke foo, b is now 'bar'

let c = () => 'bar';  // the same as defining a function. it doesn't invoke anything

let d = c;  // this doesn't invoke c.  d is now a function

let e = c();  // this *does* invoke c, e is now 'bar'

Using all that, when we say

.then(getPosts)  // this doesn't invoke getPosts

.then(getPosts(params))  // this invokes getPosts and passes the result to then

.then(() => getPosts(params))

This last formulation defines a function (unnamed) that when called (which is not yet) will invoke getPosts with params. When we pass that unnamed function to then, we're saying, "when the promise is resolved, call this unnamed function and this unnamed function will invoke getPosts"

Functions :: Eloquent JavaScript, Parameters to a function behave like regular bindings, but their initial values are given But bindings created for function parameters or declared inside a function can be If you pass too few, the missing parameters get assigned the value undefined . It then returns a function that accesses and returns this local binding. I want to pass the parameter to function. If I pass ID to parameter it is working. But I want to pass string value as parameter to function. I want to add escape sequence to the parameter.

Create a function that does what you want. Something like this:

createPost ({*post contents JSON*})
  .then(result => getPosts(param, result));

This code will wait until createPost's promise has resolved, at which time it will call getPosts, passing in param as well as the result from createPost.

Or if you don't care about the result at all, just that createPost has finished, you could do something like this:

createPost ({*post contents JSON*})
  .then(() => getPosts(param));

Always pass one argument to your JavaScript function, As a result it is easy to get confused or tied in knots about… What's happening is that JavaScript doesn't really have the same concept of a If you pass in an argument for which there is no positional label, then it is still there for which no label exists, and therefore can't be accessed inside the function? Something you can try is using the bind method, I think this achieves what you were asking for. If nothing else, it's still very useful. function doClick(elem, func) { var diffElem = document.getElementById('some_element'); //could be the same or different element than the element in the doClick argument diffElem.addEventListener('click', func.bind(diffElem, elem)) } function clickEvent(elem

Add a wrapper inline function.

createPost ({*post contents JSON*})
    .then(()=>{getPosts(param1, param2)})

Functions, Quite often we need to perform a similar action in many places of the script. If a same-named variable is declared inside the function then it We can pass arbitrary data to functions using parameters (also called function Now if the text parameter is not passed, it will get the value "no text given". JavaScript Function Scope. In JavaScript there are two types of scope: Local scope; Global scope; JavaScript has function scope: Each function creates a new scope. Scope determines the accessibility (visibility) of these variables. Variables defined inside a function are not accessible (visible) from outside the function.

createPost ({*post contents JSON*})

When you do this you are executing getPosts method at that instant and passing it's return value as parameter to the then method. If you do this instead

createPost ({*post contents JSON*})
    .then(function () {

You are waiting for the promise to resolve and executing getPosts after the promise is resolved.

Promise.prototype.then(), It takes up to two arguments: callback functions for the success and failure cases of the Promise. The behaviour of the handler function follows a specific set of rules. Also, the resolved value of the promise returned by then will be the same as the resolved if (response.headers.get('content-type') != Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what the function does, so that someone reading the code gets an indication of what the function does. It is a widespread practice to start a function with a verbal prefix which vaguely describes the action. There must be an

Functions, A function is a JavaScript procedure—a set of statements that performs a See also the exhaustive reference chapter about JavaScript functions to get to know the details. If you pass an object (i.e. a non-primitive value, such as Array or a The stack-like behavior can be seen in the following example: Passing parameters to a setTimeout() function. Any parameters that you want to pass to the function being run inside the setTimeout() must be passed to it as additional parameters at the end of the list. For example, you could refactor the previous function so that it will say hi to whatever person's name is passed to it:

JavaScript: Passing by Value or by Reference, In JavaScript, we have functions and we have arguments that we pass into those functions. When passing in a primitive type variable like a string or a number, Using the objectchanger from the last example you'd get the following: If you don't know the method of the object being passed in then you  Regardless of the language, it is generally not a good idea to reassign the parameter variables inside a function. In JavaScript it turns out to be a really bad idea. Additional information: Check out this jsFiddle to experiment with the code snippet above. A comment on this StackOverflow question describes this “magical behavior” of

JavaScript Function Parameters, A JavaScript function does not perform any checking on parameter values (​arguments). If a function is called with missing arguments (less than declared), the missing values are set to: undefined. Sometimes this is Because of this, objects will behave like they are passed by reference: If a function Get Certified »  If you pass a JavaScript string to a Java method that expects a java.lang.String argument, then you will receive a Java String, but if the signature of your method is more generic (that is, if it expects a java.lang.Object parameter, for example), you can get an object of the private engine implementation class that implements CharSequence but

  • Thanks, this helped me a lot. Could you also please take a look at the edit of my question?
  • Sure. Do you mean the why part? I was hoping the first code block and paragraph of my answer got to that. Was it unclear?
  • I'm sure you have explained it well. But I still don't understand why ()=>{getPosts(param1, param2)} does not get invoked right away, just like f() would.