首页 > 解决方案 > 如何在回调函数中显示数组

问题描述

我仍然对回调函数感到困惑。我有一个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

标签: javascriptcallback

解决方案


您正在为 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)
};


推荐阅读