nodejs回调don'我不理解回调结果是如何通过参数得出的

nodejs callback don't understand how callback result come through argument

本文关键字:回调 何通过 参数 结果是 不理解 don nodejs      更新时间:2023-09-26

看到并运行下面的代码,认为我理解闭包。。。回调参数中的"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"。

  1. 当回调("arg is odd",arg)被执行时,函数被调用为:

    • err="arg为奇数"
    • num=arg
  2. 当回调(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"