如何在node.js中创建自定义异步函数 [英] how to create a custom asynchronous function in node.js

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

问题描述

我正在尝试做类似的事情.

Ii'm trying to do something like.

function fun1(){
  for(var j=0;j<20;j++)
  {
    var n = j;
    console.log("i= "+n);
  }
}
function fun2()
{
  console.log("In Callback");
}  

fun1();
fun2();

到目前为止,一切正常,并获得了预期的输出.

its working fine till now and got output as expected.

但是,我要异步调用函数 fun1() fun2(),这意味着在 fun1之前调用 fun2()(),与 fun2()相比,b'coz fun1()需要花费一些时间才能完成执行.

But, I want to call function fun1() and fun2() asynchronously it means fun2() call before fun1(), b'coz fun1() will take some time for complete the execution as compare to fun2().

如何实现这一点,Node.js提供了异步功能,它是否已经定义为只能异步的功能,或者我们可以根据需要制作它们.

How can I achieve this, Node.js provide asynchronous function, Is it already defined function can asynchronous only or we can make them according our need.

推荐答案

有多种方法可以在JavaScript中实现此目的(不是特定于节点的,但是有一些模块可以使您的生活更轻松):

There are multiple ways to achieve this in JavaScript (not node-specific, but there are modules that make your life easier):

它们有点延续,这是可耻的开发人员手动处理它们的麻烦(编译器以前是自己做的).但它们可以工作:

They are somewhat continuations and it is a shame developers were bothered with handling them manually (compilers used to do that themselves). But they work:

function callee(callback) {
  setTimeout(function() {
    callback(null, 'finished!');
  }, 2000);
}

function caller() {
  document.write('started!');
  callee(function(err, result) {
    document.write(result);
  });
}

caller();

在节点环境中通常会用回调的第一个参数来指示错误(例如 callback(new Error("something出错!"))).

It is common in the node environment to indicate errors with the first parameter of the callback (like callback(new Error("something wrong!"))).

由于回调在嵌套时会变得很丑陋(想象其中有10-20个,您可能会被调试搞砸了),因此未来Java的它们内置于ES6中,您可以在节点环境中预先使用 npm来使用它们 -许多客户端框架(例如jQuery,AngularJS)都有自己的实现.最初有 Q .

As callbacks get ugly when nested (imagine 10-20 of them, you'd be screwed debugging this), the idea of promises came up. You might know them as Futures from java. They are built-in to ES6, and you can use them beforehand in the node environment with npm i promise -- many client-side frameworks (e.g. jQuery, AngularJS) have their own implementations. Originally there was Q.

var Promise = require('promise');

function callee() {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      resolve('finished!');
    }, 1000);
  });
}

function caller() {
  document.write('started!');
  callee().then(function(result) {
    document.write(result);
  });
}

caller();

ES6具有生成器.您可能会从 python 了解它们.

ES6 has generators. You might know them from python.

它们还提供异步功能,因为一旦计算出新值,它们就会产生新的值.

They provide asynchronity as well, as they yield new values once they are computed.

我建议阅读了解ES2015 以获得更多信息.

I recommend reading Learn ES2015 for more information on that.

我个人的观点是,永远不要使用生成器,因为它们会严重干扰Promise,并使调试变得非常困难.

ES7将通过 async / await 大大简化生活.基本上可以说一个函数将异步执行,并且您要等待结果(一旦您处于异步函数中). ES7异步功能是一个不错的开始.就像

ES7 will make life a whole lot easier with async/await. You can basically say that a function will be performed asynchronously and that you want to await a result (once you are in a async function). ES7 async functions is a good start to read on that. It's like

async function callee() {
  return (() => {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve('finished!'), 1000);
    })
  })();
}

async function caller() {
  document.write('started!');
  document.write(await callee());
}

// the global async wrapper
(async function() {
  caller();
})();

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

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