Understanding Callback

本文深入解析JavaScript中的回调函数,探讨其工作原理及如何用于处理异步操作。通过具体示例,展示了如何利用回调来组织依赖于其他函数完成的任务。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Callbacks are just functions that get executed at some later time.

The key to understanding callbacks is to realize that they are used when you don’t know when some async operation will complete, but you do know where the operation will complete — the last line of the async function!

The top-to-bottom order that you declare callbacks does not necessarily matter, only the logical/hierarchical nesting of them. First you split your code up into functions, and then use callbacks to declare if one function depends on another function finishing.

You give readFile a function (known as a callback) that it will call after it has retrieved the data from the file system.
It puts the data it retrieved into a javascript variable and calls your function (callback) with that variable.
In this case the variable is called fileContents because it contains the contents of the file that was read.

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)

Now the logMyNumber function can get passed in as an argument that will become the callback variable inside the addOne function. After the operation (readFile) is done, the callback variable will be invoked (callback()).

Only functions can be invoked, so if you pass in anything other than a function it will cause an error.

When a function gets invoked in javascript the code inside that function will immediately get executed.
当JavaScript中的函数被调用时,该函数内的代码将立即被执行。

In this case our log statement will execute since callback is actually logMyNumber(). Remember, just because you define a function it doesn’t mean it will execute. You have to invoke a function for that to happen.
请记住,你只是定义了一个函数的话,它并不意味着会被执行。 你必须调用一个函数才能触发它。

To break down this example even more, here is a timeline of events that happen when we run this program:

  1. The code is parsed, which means if there are any syntax errors they would make the program break. During this initial phase, fs and myNumber are declared as variables while addOne and logMyNumber are declared as functions. Note that these are just declarations. Neither function has been called nor invoked yet.
  2. When the last line of our program gets executed addOne is invoked with the logMyNumber function passed as its callback argument. Invoking addOne will first run the asynchronous fs.readFile function. This part of the program takes a while to finish.
  3. With nothing to do, node idles for a bit as it waits for readFile to finish. If there was anything else to do during this time, node would be available for work.
  4. As soon as readFile finishes it executes its callback, doneReading, which parses fileContents for an integer called myNumber, increments myNumber and then immediately invokes the function that addOne passed in (its callback), logMyNumber.

Perhaps the most confusing part of programming with callbacks is how functions are just objects that can be stored in variables and passed around with different names. Giving simple and descriptive names to your variables is important in making your code readable by others. Generally speaking in node programs when you see a variable like callback or cbyou can assume it is a function.

You may have heard the terms ‘evented programming’ or ‘event loop’. They refer to the way that readFile is implemented(被使用). Node first dispatches(调用) the readFile operation and then waits for readFile to send it an event that it has completed. While it is waiting node can go check on other things. Inside node there is a list of things that are dispatched but haven’t reported back yet, so node loops over the list again and again checking to see if they are finished. After they finished they get ‘processed’, e.g. any callbacks that depended on them finishing will get invoked.

Here is a pseudocode version of the above example:

function addOne(thenRunThisFunction) {
  waitAMinuteAsync(function waitedAMinute() {
    thenRunThisFunction()
  })
}

addOne(function thisGetsRunAfterAddOneFinishes() {})

Imagine you had 3 async functions a, b and c. Each one takes 1 minute to run and after it finishes it calls a callback (that gets passed in the first argument). If you wanted to tell node start running a, then run b after a finishes, and then run c after b finishes’ it would look like this:

a(function() {
  b(function() {
    c()
  })
})

     [a minute later]        [a minute later]
a() ------------------> b() ------------------> c()

When this code gets executed,

  • a will immediately start running, then a minute later a will finish and call b
  • Then a minute later b will finish and call c
  • And finally 3 minutes later node will stop running since there would be nothing more to do.

There are definitely more elegant ways to write the above example, but the point is that if you have code that has to wait for some other async code to finish then you express that dependency by putting your code in functions that get passed around as callbacks.

The design of node requires you to think non-linearly. Consider this list of operations:

read a file
process that file

If you were to turn this into pseudocode you would end up with this:

var file = readFile()
processFile(file)

This kind of linear (step-by-step, in order) code isn’t the way that node works. If this code were to get executed then readFile and processFile would both get executed at the same exact time. This doesn’t make sense since readFile will take a while to complete. Instead you need to express that processFile depends on readFile finishing. This is exactly what callbacks are for! And because of the way that JavaScript works you can write this dependency many different ways:

var fs = require('fs')
fs.readFile('movie.mp4', finishedReading)

function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
}

But you could also structure your code like this and it would still work:

var fs = require('fs')

function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
}

fs.readFile('movie.mp4', finishedReading)

Or even like this:

var fs = require('fs')

fs.readFile('movie.mp4', function finishedReading(error, movieData) {
  if (error) return console.error(error)
  // do something with the movieData
})

完结撒花

invoked - 调用

link of 很好的 callback 阐述

内容概要:本文深入解析了扣子COZE AI编程及其详细应用代码案例,旨在帮助读者理解新一代低门槛智能体开发范式。文章从五个维度展开:关键概念、核心技巧、典型应用场景、详细代码案例分析以及未来发展趋势。首先介绍了扣子COZE的核心概念,如Bot、Workflow、Plugin、Memory和Knowledge。接着分享了意图识别、函数调用链、动态Prompt、渐进式发布及监控可观测等核心技巧。然后列举了企业内部智能客服、电商导购助手、教育领域AI助教和金融行业合规质检等应用场景。最后,通过构建“会议纪要智能助手”的详细代码案例,展示了从需求描述、技术方案、Workflow节点拆解到调试与上线的全过程,并展望了多智能体协作、本地私有部署、Agent2Agent协议、边缘计算插件和实时RAG等未来发展方向。; 适合人群:对AI编程感兴趣的开发者,尤其是希望快速落地AI产品的技术人员。; 使用场景及目标:①学习如何使用扣子COZE构建生产级智能体;②掌握智能体实例、自动化流程、扩展能力和知识库的使用方法;③通过实际案例理解如何实现会议纪要智能助手的功能,包括触发器设置、下载节点、LLM节点Prompt设计、Code节点处理和邮件节点配置。; 阅读建议:本文不仅提供了理论知识,还包含了详细的代码案例,建议读者结合实际业务需求进行实践,逐步掌握扣子COZE的各项功能,并关注其未来的发展趋势。
#include <stdint.h> #include <stdbool.h> #define RAT_TICKS_PERIOD_MS 10 #define ConvertMsToRatTicks(microseconds) \ ((microseconds) / (RAT_TICKS_PERIOD_MS)) #define ONE_SHOT_MODE false #define PERIOD_MODE true /* too much timers */ typedef enum { BEEP_TIMER, RTC_TIMER, NFC_TIMER, NFC_DELAY_TIMER, CARD_TIMER, DEV_REP_TIMER, DEV_DELAY_TIMER, PULSE_TIMER, PAUSE_TIMER, APPOINT_TIMER, AT_DELAY_TIMER, AT_RX_TIMER, GPRS_DELAY_TIMER, GPRS_SEND_TIMER, GPRS_TIMEOUT_TIMER, GPRS_HEARTBEAT_TIMER, GPRS_KEEPALIVE_TIMER, LCD_TICK_TIMER, LCD_TIPS_TIMER, LCD_PAGE_TIMER, LCD_RST_TIMER, LCD_BK_TIMER, OTA_DELAY_TIMER, OTA_TIMEOUT_TIMER, NUM_OF_TIMER }timer_id_t; typedef void (*TimerCallbackFunction_t)(void); /* Define the Timer Control Block data type. */ typedef struct TM_TCB_STRUCT { const char *pcTimerName; /* Timer name for debug */ volatile bool tm_auto_reload; /* One_shot/Period */ volatile bool tm_enabled; /* Timer enabled flag */ volatile bool tm_expirations; /* Number of expirations */ TimerCallbackFunction_t pxCallbackFunction; volatile uint32_t tm_initial_time; /* Initial time */ volatile uint32_t tm_reschedule_time; /* Reschedule time */ } TM_TCB; void SoftTimer_Create( const char* pcTimerName, const uint8_t pvTimerID, bool AutoReload, uint32_t timerTicks, TimerCallbackFunction_t callback ); extern TM_TCB TimerList[NUM_OF_TIMER]; void SoftTimer_Init(void); void SoftTimer_Start(const uint8_t pvTimerID); void SoftTimer_Change_Period(const uint8_t pvTimerID, uint32_t timerTicks); void SoftTimer_Stop(const uint8_t pvTimerID); void SoftTimer_Process(void);
07-15
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值