Skip to content
Advertisement

How to display array in Callback Function

I still confuse about callback function. I have a task to displays month using callback function, so I try to call my function getMonth for displays month and this is so far I got. I haven’t used Javascript before, so any help would be appreciated

const getMonth = (callback) => {
    setTimeout(()=>{
        let error = false;
        let month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December']
        if(!error){
            callback(null, month)
            
        } else {
            callback(new Error('Sorry Data Not Found', []))
        }
    }, 4000)
};

getMonth((err,result)=>{
    if(err){
        console.log(new Error(err)); //the output I want is: Sorry Data Not Found
    }
    console.log(err,result); //the output I want is::['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December']
})

my output is:

setTimeout is not a function

Advertisement

Answer

You are assigning a function to setTimeout instead of puting the function as parameter of setTimeout

Just put the function as the first parameter of the setTimeout and you’re ready to go

const getMonth = (callback) => {
    setTimeout(() => {
        let error = false;
        let month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October','November', 'December']
        if(!error){
            callback(null, month)
            
        } else {
            callback(new Error('Sorry Data Not Found', []))
        }
    }, 4000)
};
Advertisement