如何在回调函数中显示数组

How to display array in Callback Function

我仍然对回调函数感到困惑。我有一个使用回调函数显示 month 的任务,所以我尝试调用我的函数 getMonth 来显示 month,到目前为止我已经完成了。我以前没有使用过 Javascript,所以任何帮助将不胜感激

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']
})

我的输出是:

setTimeout is not a function

您正在为 setTimeout 分配一个函数,而不是将该函数作为 setTimeout 的参数

只需将该函数作为 setTimeout 的第一个参数即可开始

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)
};