Node.js:如何以编程方式确定异步? [英] Node.js: How to programmatically determine asynchronous?

查看:196
本文介绍了Node.js:如何以编程方式确定异步?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够接受一个不接受回调的函数,并确定它是否会异步执行。

I'd like to be able to take a function that doesn't take a callback and determine if it will execute asynchronously.

特别是,我是使用 mraa 在英特尔Edison上使用Node.js,它具有本机C ++实现的功能喜欢 i2c.readReg(地址)但不接受回调。

In particular, I'm working with Node.js on the Intel Edison using mraa, and it has native C++ implemented functions like i2c.readReg(address) that doesn't accept a callback.


  1. 如何判断某个函数是否阻塞了其他系统进程的处理器?

  2. 如何确定其他JS是否可以在此期间运行?

或者我是不是以正确的方式接近这个?

Or am I not even approaching this the right way?

推荐答案

你无法以编程方式确定异步性。从API中可以清楚地看出,如果它是异步的,那么在你使用它的方式中几乎必须有这个迹象。

You can't really determine asynchronicity programmatically. It should be clear from the API presented because if it's asynchronous, then there pretty much have to be signs of that in the way you use it.

如果一个函数是异步的,那意味着它不直接从函数调用返回结果,因为函数在结果准备好之前返回。因此,函数的文档必须告诉您如何获取结果,如果它是异步的,则必须有另一种机制,例如:

If a function is asynchronous, then that means that it does not directly return the result from the function call because the function returns before the result is ready. As such, the documentation for the function has to tell you how to obtain the result and if it's asynchronous there has to be another mechanism such as:


  1. 你可以传入的回调函数

  2. 返回的承诺

  3. 对象上的某种事件监听器

  4. 其他一些通知机制

  5. 检查函数的代码

  6. 函数命名约定(例如后缀) node.js使用的同步)

  1. a callback function you can pass in
  2. a returned promise
  3. some sort of event listener on the object
  4. some other notification mechanism
  5. examine the code of the function
  6. function naming convention (such as the suffix "Sync" that node.js uses)

如果函数直接返回函数调用的结果,那么它是同步的和其他的在该调用期间,Javascript代码将无法运行。

If the function directly returns the result of the function call, then it is synchronous and other Javascript code will not run during that call.

如果函数尚未异步,则将其转换为异步操作是在不同的线程或进程中运行它并将值编组回主线程(当值准备就绪时在主线程中调用某种回调)。

If a function is not already asynchronous, the only way to turn that into an async operation is to run it in a different thread or process and marshall the value back to the main thread (calling some sort of callback in the main thread when the value is ready).

这篇关于Node.js:如何以编程方式确定异步?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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