Cube
Cube

Reputation: 119

Understanding Callback function

i have trouble with the following code:

var placeingOrders = function(orderNumber) {
    console.log("Order number: ", orderNumber);
    requestedOrder(orderNumber, returnOrder);
};

function requestedOrder(orderNumber, callback) {
    setTimeout(orderNumber, callback, 5000);
}

function returnOrder() {
    console.log("Order number: " ,  " is delivered");
}

im trying to pass arguments on callback function but when i do as above i got the following error code:

timers.js:348
    throw new TypeError('"callback" argument must be a function');
    ^

TypeError: "callback" argument must be a function
    at exports.setTimeout (timers.js:348:11)

And of course if i run the same code without arguments it will work.

var placeingOrders = function(orderNumber) {
    console.log("Order number: ", orderNumber);
    requestedOrder(returnOrder);
};

function requestedOrder(callback) {
    setTimeout(callback, 5000);
}

function returnOrder() {
    console.log("Order number: " , orderNumber , " is delivered");
}

I would like to know what im exactly doing wrong here. How do i use this callback function correctly if i want to pass arguments.

(ps: im not a native english speaker, sry for that)

Upvotes: 1

Views: 267

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68685

Why you get this error ?

setTimeout expects to get the callback function as the first argument, but at the first place you pass a number, so why the exception. The second case works, because you remove the orderNumber from the first place, an the function gets it.

You need to pass the arguments of the callback function after the 2nd place. See the setTimeout function signature. First goes the callback function, 2nd - the time, at least to call the function and after it everything which are passed goes to the callback function as arguments.

This is the signature of the function - [] are optional ones.

setTimeout(function[, delay, param1, param2, ...])

Code

var placeingOrders = function(orderNumber) {
   console.log("Order number: ", orderNumber);
   requestedOrder(orderNumber, returnOrder);
};
    
function requestedOrder(orderNumber, callback) {
    setTimeout(callback, 5000, orderNumber);
}
    
function returnOrder(orderNumber) {
    console.log("Order number: " + orderNumber +  " is delivered");
}

placeingOrders(14);

Upvotes: 4

Related Questions