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

查看:136
本文介绍了如何写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.

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

另一种方式来问我的问题是这样的:?我应该怎样间preT下面的函数

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);
    });
};

另外,我发现的 this在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是更好的。最好的方法去理解它是去了瑞安达尔观看一些影片。

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.

我如何编写异步功能节点?

只写正常功能,唯一的区别是,他们不会立即执行,但传来传去的回调。

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

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

一般的API给你一个犯错作为第一个参数的回调。例如:

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);
});

是一种常见的模式。

Is a common pattern.

另一种常见的模式是对('错误')。例如:

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_function 这调用堆栈是空的,的console.log(43)已运行。因此,我们打印其次是42 43。

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天全站免登陆