如何为 Node.js 编写异步函数 [英] How to write asynchronous functions for Node.js

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

问题描述

我试图研究应该如何编写异步函数.在翻阅了大量文档后,我仍然不清楚.

I've tried to research on how exactly asynchronous functions should be written. After a lot of plowing through a lot of documentation, it's still unclear to me.

如何为 Node 编写异步函数?我应该如何正确实现错误事件处理?

问我问题的另一种方式是:我应该如何解释以下函数?

Another way to ask my question would be this: How should I interpret the following function?

var async_function = function(val, callback){
    process.nextTick(function(){
        callback(val);
    });
};

另外,我发现 关于 SO 的这个问题(如何在 node.js 中创建非阻塞异步函数?")很有趣.我觉得还没有人回答.

Also, I found this question on SO ("How do I create a non-blocking asynchronous function in node.js?") interesting. I don't feel like it has been answered yet.

推荐答案

您似乎将异步 IO 与异步函数混淆了.node.js 使用异步非阻塞 IO,因为非阻塞 IO 更好.理解它的最好方法是观看 ryan dahl 的一些视频.

You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.

如何为 Node 编写异步函数?

只需编写普通函数,唯一的区别是它们不会立即执行,而是作为回调传递.

Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.

我应该如何正确实现错误事件处理

通常,API 会给您一个回调,并将 err 作为第一个参数.例如

Generally API's give you a callback with an err as the first argument. For example

database.query('something', function(err, result) {
  if (err) handle(err);
  doSomething(result);
});

是一种常见的模式.

另一种常见模式是on('error').例如

Another common pattern is on('error'). For example

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});

var async_function = function(val, callback){
    process.nextTick(function(){
        callback(val);
    });
};

当调用为上述函数时

async_function(42, function(val) {
  console.log(val)
});
console.log(43);

将异步打印 42 到控制台.特别是 process.nextTick 在当前事件循环调用堆栈为空后触发.async_functionconsole.log(43) 运行后,该调用堆栈为空.所以我们打印 43 然后是 42.

Will print 42 to the console asynchronously. In particular process.nextTick fires after the current eventloop callstack is empty. That call stack is empty after async_function and console.log(43) have run. So we print 43 followed by 42.

您可能应该对事件循环进行一些阅读.

You should probably do some reading on the event loop.

这篇关于如何为 Node.js 编写异步函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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