javascript - 如何在回调函数中显示数组
问题描述
我仍然对回调函数感到困惑。我有一个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)
};
推荐阅读
- r - 在带有 sapply 的函数中使用 str_split 和 union 的意外结果
- c# - C# JSON 反序列化异常
- android - 未找到资源,但仅在看似随机的设备上
- html - 使用 HTML Geolocation API 的坐标错误
- excel - EXCEL 中的 IF/THEN 嵌套公式
- angular - Angular - 如何显示对象数组
- python - 在 Windows 中使用 Ctypes 加载 DLL 后调用函数挂起
- excel - 如何在 VBA 中格式化特定的邮件值
- response - 匹配失败时 Wiremock 禁用响应
- input - 当涉及到 XSS 时,转义和编码是如何工作的?