nodejs回调don'我不理解回调结果是如何通过参数得出的
nodejs callback don't understand how callback result come through argument
看到并运行下面的代码,认为我理解闭包。。。回调参数中的"avatarUrl"是如何在"avatar"中接收的,"avatar"也是函数参数。我知道这是常见的模式,只是还不能得到它
var GitHubApi = require('github');
var github = new GitHubApi({
version: '3.0.0'
});
var getUserAvataWithCallback = function(user, callback) {
github.search.users({q: user}, function(err,res) {
if (err) { callback(err, null);}
else {
var avatarUrl = res.items[0].avatar_url;
callback(null, avatarUrl);
}
});
};
getUserAvataWithCallback('irom77', function(err,avatar) {
console.log('got url with callback pattern', avatar);
})
因此,回调是javascript中的一个基本概念,因此了解一些概念非常重要。看看这个例子:
// This is the function definition for "foo"
//here the callback argument refers to
//the second argument in the function call at
//the bottom which is a function
var foo = function(arg, callback) {
if(arg%2 != 0)
callback("arg is odd", arg)
else
callback(null, arg)
}
//Function call to foo
foo(2, function(err, num) {
if(err)
console.log(err)
else
console.log(num)
}
因此,在上面的例子中,您可以将函数调用视为具有两个参数的调用,即整数2和一个函数。
在函数定义中:
整数称为"arg",函数称为"callback"。
-
当回调("arg is odd",arg)被执行时,函数被调用为:
- err="arg为奇数"
- num=arg
-
当回调(null,arg)被执行时,函数会被调用:
- err=null
- num=arg
这里需要记住的重要一点是,在javascript中,函数可以作为参数传递给其他函数。请在此处进一步阅读。
传递给函数的参数的名称不需要是函数定义中参数的名称,定义中的参数是将在给定函数范围内初始化的变量的名称。参数声明将接收在函数调用的第二个位置传递的值(根据您提供的代码),并且您将能够在具有该名称的范围内访问它。您可以:
function foo(arg1, arg2) {
console.log(arg1, arg2);
}
foo(true, true); // will output true, true
foo(0, 1); //will output 0, 1
foo('shikaka', 1); //will output "shikaka", 1
var bar = "shikaka";
foo(bar, "shikaka"); //will output "shikaka", "shikaka"
相关文章:
- 通过回调从onreadystatechange返回值
- 如何通过bxSlider回调api处理事件
- 访问通过XHR.onreadystatechange回调中的XHR.send(data)发送的数据
- 使用Javascript通过ajax回调更新DOM
- 如何通过回调函数设置值
- $.mobile.changePage 之后的回调函数通过 AJAX 加载
- 如何通过一个回调异步排队和执行多个promise
- 未通过单击按钮调用JavaScript回调
- 当通过Ajax成功回调更新可观察数组时,启用绑定中断
- 如何通过回调访问nodejs中的mongodb计数结果
- 通过带有err,value签名的回调创建promise
- jQuery通过父函数返回$.post回调
- Sequelize等待,直到循环通过回调结束
- 通过Window.open的Web意向回调事件只是没有发生
- socket.io (nodejs) 是否通过在回调完成期间阻止服务器来影响服务器性能
- 通过AjaxForm提交图像并执行回调
- 使用 jQuery 回调参数通过 AJAX 调用 PHP 函数
- _googWcmGet回调无法通过具有动态电话号码的GTM工作
- -父组件回调如何通过子道具接收参数顺序/值
- 如何注册一个回调并通过网站刷新持久化它