回调无法正常工作 - Javascript
我有一个(异步)功能,可以在Chrome中获取登录用户的ID。我试图用回调函数返回ID的值,但是它一直返回'undefined'。回调无法正常工作 - Javascript
之前有人试图以纪念这一个重复的,我使用的代码从这里(和尝试过其他地方也是如此):How to return value from an asynchronous callback function?但它没有工作:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
callback(userInfo.id);
});
}
getGaia(function(id){
return id;
});
var gaiaId = getGaia();
我得到以下错误:
'callback' is a not a function
我究竟在做什么错误/什么是正确的代码?
那是因为你没有提供回调。
function doSomethingLater(callback) {
setTimeout(callback, 1000);
}
console.log('This is before the callback');
doSomethingLater(function() {
console.log('This is the callback')
});
所以,当你调用var gaiaId = getGaia();
你是不是传递一个回调函数
[编辑]这是你的代码需要什么样子:
function getGaia(callback) {
chrome.identity.getProfileUserInfo(function(userInfo){
var userId = userInfo.id;
// This will call the function that you pass in below
//and pass in userInfo.if as a parameter
callback(userInfo.id);
});
}
var gaiaId = getGaia(function (id) {
// id === userInfo.id from above
// Do something with the id that you pass in
});
你可以想像JavaScript中的变量这样的函数,
所以,你可以指定一个函数来像这样的变量:
var foo = function() { ... }
这意味着你可以传递到像正常变量函数这一点。当你传递给函数作为一个参数,要指定您在参数中指定的函数名称:
var foo = function() { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
所有我在上面做,而不是创建变量foo
我刚刚创建的功能内联:
var foo = function() { ... }
function hasCallback(callback) {
// The following two line do exactly the same thing:
callback(); // Using the function that you passed in
foo(); // Using the function directly
}
hasCallback(foo);
// Becomes:
function hasCallback(callback) {
callback(); // Using the function that you passed in
}
hasCallback(function() { ... });
那么我的代码应该是什么样子? – JamesJameson2456
基本上,您必须设置任何变量并处理回调中与'Gaia'' ID'相关的所有逻辑。 – Seth
@ JamesJameson2456查看编辑 –
您确定使用'callback'或'Callback'吗?该错误表示您正在使用“回拨”。但是你的代码有小写回调。 – zero298
错误,'回调'是不是一个函数,在这里C是回调的资本 –
已编辑 - 这是一个错字 – JamesJameson2456