简体   繁体   English

使用回调和调用方法之间的区别

[英]Difference between using callbacks and calling methods

I'm very new to Javascript programming and was researching ways in dealing with asynchronous functions. 我对Javascript编程非常陌生,正在研究处理异步函数的方法。 I came across really helpful resource which lists this as an example: 我遇到了非常有用的资源,该资源将其列为示例:

var fs = require('fs')
var myNumber = undefined

function addOne(callback) {
    fs.readFile('number.txt', function doneReading(err, fileContents) {
        myNumber = parseInt(fileContents)
        myNumber++
        callback()
    })
}

function logMyNumber() {
    console.log(myNumber)
}

addOne(logMyNumber)

However could you achieve the same result doing this: 但是,您可以通过执行以下操作获得相同的结果:

var fs = require('fs')
var myNumber = undefined

function addOne() {
    fs.readFile('number.txt', function doneReading(err, fileContents) {
        myNumber = parseInt(fileContents)
        myNumber++
        logMyNumber()
    })
}

function logMyNumber() {
    console.log(myNumber)
}

addOne()

And if you can, what would be the purpose/advantage of using callbacks? 如果可以的话,使用回调的目的/优势是什么?

For those interested the article came from here: https://github.com/maxogden/art-of-node#callbacks 对于那些感兴趣的人,文章来自这里: https : //github.com/maxogden/art-of-node#callbacks

When we use call back it depend on situation in to make things dynamic or make sure that a code of piece run after one is complete.in your current code already describe callbacks 当我们使用回调时,它取决于情况以使事情动态化或确保一段代码完成后运行。在您当前的代码中已经描述了回调

your first example clearly state how we define callbacks. 您的第一个示例清楚地说明了我们如何定义回调。

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. 在计算机编程中,回调是一段可执行代码,将其作为参数传递给其他代码,希望在某些方便的时间回调(执行)该参数。 The invocation may be immediate as in a synchronous callback, or it might happen at later time as in an asynchronous callback 调用可能像同步回调中​​一样是立即调用,也可能像异步回调中一样在稍后发生

var fs = require('fs')
var myNumber = undefined

you are using call back here which give you power to run different- different method after reading number.txt successfully 您正在此处使用回叫功能,这使您可以在成功阅读number.txt后运行不同的方法

function addOne(callback) {
    fs.readFile('number.txt', function doneReading(err, fileContents) {
        myNumber = parseInt(fileContents)
        myNumber++
        callback()
    })
}

in your second example there is no callback you are calling logMyNumber() directly, what if we need to run another function something like 在第二个示例中,没有回调,您直接调用logMyNumber(),如果我们需要运行另一个函数,例如

function logMyNumber() {
    console.log(myNumber)
}

function varifynumber() {
    console.log(myNumber)
}

function somthingelse() {
    console.log(myNumber)
}


addOne(logMyNumber)
addOne(somthingelse)
addOne(logMyNumber)

and the other best use of callbacks in JavaScript is handle asynchronous tasks, if you noticed inside your function you are using fs.readFile('number.txt',callback) which is a asynchronous method please have look below example JavaScript中回调的另一种最佳用法是处理异步任务,如果您在函数内部注意到使用的是fs.readFile('number.txt',callback)这是一种异步方法,请查看以下示例

console.log('start');
 fs.readFile('number.txt', function doneReading(err, fileContents) {
          // until the file not read completely this section will not run 
          // this happend because of call back  
        console.log('Reading complete');
        })
console.log('End');

output :
start
End
Reading complete

i hope this will help you 我希望这能帮到您

It all depends on what you are trying to achieve. 这完全取决于您要实现的目标。 In the first example, the function addOne has no concept on what the callback parameter does, it just invokes it. 在第一个示例中,函数addOne对回调参数的作用没有任何概念,它只是调用它。

However, in the second case, the addOne function knows it will invoke logMyNumber , and therefore has a tighter coupling and concept of what exactly is going on. 但是,在第二种情况下, addOne函数知道它将调用logMyNumber ,因此具有更紧密的耦合以及确切的含义。

The first example is often favorable in most cases, eg if you are splitting functions across multiple files, and don't want them to be tightly intertwined. 在大多数情况下,第一个示例通常是有利的,例如,如果要在多个文件之间拆分函数,并且不希望它们紧密地缠绕在一起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM