如何确定回调将要同步还是异步执行? [英] How to identify if a callback is going to be executed synchronously or asynchronously?

查看:149
本文介绍了如何确定回调将要同步还是异步执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习node.js。到目前为止,我已经了解了回调的含义,但是我不确定是要同步执行回调(调用者直到回调返回之前才继续执行)还是异步执行(调用者进行回调并继续执行其代码)。

I am learning node.js. By now, I have understood what callback means but I am not sure whether a callback is going to be executed synchronously(the caller not proceeding ahead until the callback returns) or asynchronously(the caller making a callback and proceeding ahead with its code).

推荐答案

您不能通过查看函数调用来真正分辨出来。 某些回调是异步的,而其他则不是。您需要检查文档,并在其中注明。

You cannot really tell by looking at the function invocation. Some callbacks are asynchronous, others are not. You will need to check the docs, it will should be stated there.

通常您可以通过函数签名来区分它们。如果期望某个回调仅在计算结果中被调用一次,并且该回调和该函数均未返回任何内容,则该回调通常是异步调用的( setTimeout readFile 等)。如果函数立即返回结果,则通常会多次调用回调( Array :: sort Array :: map )并产生有价值的价值。当然,例外证明了规则,有时您无法轻易分辨,例如 setInterval Array :: forEach (均不返回任何内容,并多次调用该回调)。

Often you can tell them apart by the function's signature. If a callback is expected to be called only once with the result of a computation, and neither the callback nor the function don't return anything, the callback is usually invoked asynchronously (setTimeout, readFile etc). If the function returns the result immediately, the is typically callback invoked multiple times synchronously (Array::sort, Array::map) and yields valuable values. Of course, the exception proves the rule, and sometimes you cannot tell easily, e.g. setInterval vs Array::forEach (both return nothing, and invoke the callback multiple times).

这篇关于如何确定回调将要同步还是异步执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆