你如何创建自定义的Node.js异步函数? [英] How do you create custom asynchronous functions in node.js?

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

问题描述

我不确定Node.js的是如何能够实现哪些功能异步哪里,哪些不是,如何创建一个自定义功能ansyc

I was unsure how node.js was able to realize what functions where async and which were not and how to create a custom ansyc function.

说我想创建一个自定义的异步的。我会感到惊讶,如果仅仅是因为我打电话给我的最后一个参数的异步回调函数或CB,它将只知道它的异步功能:

Say I wanted to create a custom asynchronous. I would be surprised if just because I called my last argument to the async function callback or cb that it would just know its an async function:

function f(arg1, callback){
  //do stuff with arg1
  arg1.doStuff()
  //call callback
  callback(null, arg1.result());
}

我试过类似的东西,并没有奏效异步。你怎么知道的node.js f是实际异步?

I tried something like that and it did not work async. How do you tell node.js that f is actually async?

推荐答案

要在其上创建一个异步函数,你必须有一些异步原语(一般IO相关) - 定时器,从文件系统读取,发出请求等

To create an asynchronous function, you have to have some async primitive (typically IO-related) on it - timers, reading from the filesystem, making a request etc.

例如,该功能需要一个回调参数,经过100毫秒调用它:

For example, this function takes a callback argument, and calls it 100ms after:

function async(callback) {
  setTimeout(function() {
    callback();
  }, 100);
}

一个可能的原因用于制造功能异步时,它并不需要是,为的API一致性。例如,假设你有一个函数,使一个网络请求,并缓存供以后调用的结果:

A possible reason for making a function async when it doesn't need to be, is for API consistency. For example, suppose you have a function that makes a network request, and caches the result for later calls:

var cache = null;
function makeRequest(callback) {
  if(!cache) {
    makeAjax(function(result) {
      cache = result;
      callback(result);
    });
  } else {
    callback(cache);
  }
}

问题是,这个功能是不一致的:有时它是异步的,有时不是。假设你有一个消费者是这样的:

The problem is, this function is inconsistent: sometimes it is asynchronous, sometimes it isn't. Suppose you have a consumer like this:

makeRequest(function(result) { doSomethingWithResult(result); });
doSomethingElse();

doSomethingElse 功能可能之前或 doSomethingWithResult 函数运行后,根据结果是否缓存与否。现在,如果你使用一个异步的 makeRequest的功能简陋,如的 process.nextTick

The doSomethingElse function may run before or after the doSomethingWithResult function, depending on whether the result was cached or not. Now, if you use an async primitive on the makeRequest function, such as process.nextTick:

var cache = null;
function makeRequest(callback) {
  if(!cache) {
    makeAjax(function(result) {
      cache = result;
      callback(result);
    });
  } else {
    process.nextTick(function() callback(cache); });
  }
}

该电话永远是异步,而 doSomethingElse 总是 doSomethingWithResult

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

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