我试图通过简单地创建一个带两个数字的函数来学习回调函数,并且有一个返回我的数组中最后一项的回调。我是一名自学成才的网络开发人员,所以如果可能的话,我希望有一些专家来教育我。
这是我的代码
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
function last(arr, cb) {
// last passes the last item of the array into the callback.
// console.log(arr.pop())
return cb(arr[arr.length - 1])
}
last(items, cb)
我的错误是:未捕获TypeError:cb不是函数
如果你想使用回调cb
,那么你需要定义它。像这样
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
const cb = x => {
console.log('last item is:', x);
return x;
}
function last(arr, cb) {
return cb(arr[arr.length - 1])
}
last(items, cb);
您需要创建一个回调。使用以下代码:
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
function last(arr, cb) {
// last passes the last item of the array into the callback.
// console.log(arr.pop())
return cb(arr[arr.length - 1]);
}
last(items, e => { console.log(e) });
回调是一个函数,它作为参数传递给另一个函数,并从其中调用以继续该程序。您在代码中缺少回调函数。这是简单的一点。
现在,你的问题中的这句话需要更多的工作:
一个函数,它接受两个数字,并有一个返回最后一项的回调
对于没有涉及异步过程的示例,这当然很好...
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
function last(arr, cb) {
const el = arr[arr.length - 1];
return cb(el);
}
const lastItem = last(items, function print(el) {
return `Last element is ${el}`;
});
console.log(lastItem);
...但通常你会看到回调主要用于在异步进程运行后继续代码流,并且在这种情况下你不能从回调中返回值。
例如,在这个例子中,我们使用setTimeout
来延迟调用2s的回调:
const items = ['Pencil', 'Notebook', 'yo-yo', 'Gum'];
function last(arr, cb) {
const el = arr[arr.length - 1];
setTimeout(() => {
cb(el);
}, 2000);
}
last(items, function print(el) {
console.log(`Last element is ${el}`);
});
我们没有返回任何东西因为返回setTimeout
毫无意义,也没有返回setTimeout
内的回调。相反,我们在2s之后使用值调用回调,并将字符串记录到控制台。
这意味着我们不能像第一个例子中的lastItem
那样将变量值返回给变量,而"How do I return the response from an asynchronous call"可能是此网站上链接最多的问题的原因,重要的是你明白这一点是为了你的理解回调。
因此,虽然您可以从回调中返回值,但通常会在异步过程之后继续执行程序。
希望有所帮助。