Wednesday, April 22, 2020

Implicit Argument to JavaScript Promise

I came across some code at work that I did not understand. After doing a little digging, I learned something I did not know about Promises. If you have a single argument to a function, you can use an implicit argument. What does the mean? Let's start with an example:
test(0)
 .then((results) => test(results))
 .then((results) => test(results))
 .then((results) => { console.log(`Results from first test: ${results}`) });

function test(arg) {
 return new Promise((resolve, reject) => {
  resolve(arg + 1);
 });
}
So what's happening here? I am passing the number zero to the function test. It is taking that number, adding one to it, and returning a new Promise. .then((results) => test(results) then takes that result and passes it to the test function again which again adds one and returns a new Promise. Finally, we are printing the result which is 3. Now here is a different way to write that code with an implicit argument:
test(0)
 .then(test)
 .then(test)
 .then(results => { console.log(`Results from second test: ${results}`) });

function test(arg) {
 return new Promise((resolve, reject) => {
  resolve(arg + 1);
 });
}

The result is the same. In this case, .then(test) is the equivalent of .then((results) => test(results)). This shorthand notation only works for a single argument. If you have multiple arguments to your function, you will have to write out the full code.

0 comments:

Post a Comment

 
Blogger Templates