top of page
Search
Writer's pictureSiah Peih Wee

Understanding Function and Methods Chaining

Updated: Aug 5, 2022

What is a Function?

Let's watch a video what is the concept of function and how to read the syntax.


Here is an example of usage

function Square(nValue)
{
    var nSquare = nValue * nValue;
    return nSquare;
}

var nComputed = Square(5);

Noticed that the variable will take the return value from the method Square().


Here is an example of usage delayed by 5 seconds. This is using setTimeout to run Square function after a period time. And in this case is 5000 milliseconds, which is 5 seconds.

function Square(nValue)
{
    var nSquare = nValue * nValue;
    return nSquare;
}

var nComputed;

setTimeout(function(){
    nComputed = Square(5);
}, 5000);

How about parameters? The example below show that setTimeout will pass in the parameter 5 into the function as nValue. Notice this function in setTimeout doesn't have a name?

function Square(nValue)
{
    var nSquare = nValue * nValue;
    return nSquare;
}
var nComputed;
setTimeout(function(nValue){
    nComputed = Square(nValue);
}, 5000, 5);

What are Anonymous Functions?

The function highlighted in the code shown below has no name, therefore it is an Anonymous function. This is used when you do not need to access it after initial creation like the case shown below. It will only be used by setTimeout and not used in subsequent codes.

function Square(nValue)
{
    var nSquare = nValue * nValue;
    return nSquare;
}
var nComputed;
setTimeout(function(nValue){
    nComputed = Square(nValue);
}, 5000, 5);

You might want to read up more about


What are Arrow Functions?

Noticed the highlighted function written below is different from the Anonymous Function? This is another way to declare a function, called Arrow Function. The first (nValue) is parameter of the function and => is the declaration of the function in arrow format.

function Square(nValue)
{
    var nSquare = nValue * nValue;
    return nSquare;
}
var nComputed;
setTimeout((nValue) => {
    nComputed = Square(nValue);
}, 5000, 5);

You might want to read up more about


Why Some Call Them Methods?


Lets take a look below, noticed when we declare the function as an Anonymous Function.

  • A method is a function, but a function may not be a method.

  • A function becomes a method when it is a function of an object.


Read up more about the differences and find out how it really works.


Methods Chaining

If you have read my article on Query Server via Axios, you will notice Axios function looks abit different. It has a chain of methods called before the end with semi-colon " ; "

axios.get('http://localhost:3000/ROUTE/', {message:"Hello"})
    .then((response) => {
    
    })
    .catch(function(error) {
    
    });

There are 3 methods show in the chain. The first is the get method.

axios.get('http://localhost:3000/ROUTE/', {message:"Hello"})
    .then((response) => {
    
    })
    .catch(function(error) {
    
    });

The get method has 2 parameters, The first is the URL to query, second is the parameters to send over.

axios.get('http://localhost:3000/ROUTE/', {message:"Hello"})
    .then((response) => {
    
    })
    .catch(function(error) {
    
    });

The get method will then have a Promise object returned which allow the method then().

axios.get('http://localhost:3000/ROUTE/', {message:"Hello"})
    .then((response) => {
    
    })
    .catch(function(error) {
    
    });

Noticed the then() is using Arrow Function format? The method then() will return a Promise object with the method catch().

axios.get('http://localhost:3000/ROUTE/', {message:"Hello"})
    .then((response) => {
    
    })
    .catch(function(error) {
    
    });

Noticed the catch() is using Anonymous Function format?

axios.get('http://localhost:3000/ROUTE/', {message:"Hello"})
    .then((response) => {
    
    })
    .catch(function(error) {
    
    });


Lets look at an example on Chaining


For source code of the full example. You can find it at


Setup an API in Express for Axios to Query


First we need to have an Express server with the following API which return a random 4 digits number.

If you do not know how to setup an Express server, do read up my previous article on Create Backend using Postgres + Express
app.get('/generate4d', async (req, res, next) => {
    console.log(req.body);
    let iRandom4D = Math.floor(Math.random() * 10000);
    res.json({result: iRandom4D});
});


Example of Methods Chaining


Now using the knowledge you learnt earlier. Interpret the Methods Chaining inside the function Generate4D(). You will also notice that methods chaining can be chained as much as you want.


Try modify one of the get method's Query URL to an invalid URL, see how the chaining works.

/////////////////////////////////////////////////////////////////////
// Function to Display Server Response
/////////////////////////////////////////////////////////////////////
function DisplayResponse(objData)
{   
    txtDisplay.append(objData + "   ");
}

/////////////////////////////////////////////////////////////////////
// Function to Clear Display
/////////////////////////////////////////////////////////////////////
function ResetDisplay()
{   
    txtDisplay.innerHTML = "";
}

/////////////////////////////////////////////////////////////////////
// Function to Force Delay Between Chain
/////////////////////////////////////////////////////////////////////
function WaitAwhile(delay) 
{
    return function(response)
    {
        return new Promise(resolve => {
            setTimeout(() => resolve(response), delay)
        });
    };
}

/////////////////////////////////////////////////////////////////////
// Function to Try Axios -> Promise Chain 
/////////////////////////////////////////////////////////////////////
function Generate4D()
{
    ResetDisplay();

    axios.get('http://localhost:3000/generate4d/', {})
    .then((response) => {
        console.log(response.data); //View in Browser's Developer Tools
        DisplayResponse(response.data.result); //Look for result in response
        return axios.get('http://localhost:3000/generate4d/', {});
    })
    .then(WaitAwhile(1000))
    .then((response) => {
        console.log(response.data); //View in Browser's Developer Tools
        DisplayResponse(response.data.result); //Look for result in response
        return axios.get('http://localhost:3000/generate4d/', {});
    })
    .then(WaitAwhile(1000))
    .then((response) => {
        console.log(response.data); //View in Browser's Developer Tools
        DisplayResponse(response.data.result); //Look for result in response
        return axios.get('http://localhost:3000/generate4d/', {});
    })
    .then(WaitAwhile(1000))
    .then((response) => {
        console.log(response.data); //View in Browser's Developer Tools
        DisplayResponse(response.data.result); //Look for result in response
    })
    .catch(function(error) {
        DisplayResponse(error);
    })
}

NOTE: WaitAwhile() is made to connect the Axios methods chaining with delay.

You might want to read up more about

If you want to see more method chaining in action, below is an example. To view the console's print line, you will need to click "Open on Replit"


302 views0 comments

Comments


Post: Blog2 Post
bottom of page