简体   繁体   English

如何在 node.js 中创建自定义异步函数

[英]how to create a custom asynchronous function in 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.到目前为止,它的工作正常,并按预期获得了输出。

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() .但是,我想通话功能fun1()fun2()异步意味着fun2()之前调用fun1() ,b'coz fun1()作为比较会需要一些时间完成执行fun2()

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.我怎样才能做到这一点,Node.js 提供异步功能,它是已经定义的功能只能异步还是我们可以根据需要制作它们。

There are multiple ways to achieve this in JavaScript (not node-specific, but there are modules that make your life easier):在 JavaScript 中有多种方法可以实现这一点(不是特定于节点的,但有一些模块可以让您的生活更轻松):


callbacks回调

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

It is common in the node environment to indicate errors with the first parameter of the callback (like callback(new Error("something wrong!")) ).在节点环境中,用回调的第一个参数来指示错误是很常见的(比如callback(new Error("something wrong!")) )。


promises承诺

As callbacks get ugly when nested (imagine 10-20 of them, you'd be screwed debugging this), the idea of promises came up.由于回调在嵌套时变得丑陋(想象其中有 10-20 个,你会被调试这个搞砸), promise的想法出现了。 You might know them as Futures from java.您可能将它们称为 Java 中的Futures They are built-in to ES6, and you can use them beforehand in the node environment with npm i promise -- many client-side frameworks (eg jQuery, AngularJS) have their own implementations.它们是 ES6 内置的,您可以预先在节点环境中使用npm i promise ——许多客户端框架(例如 jQuery、AngularJS)都有自己的实现。 Originally there was Q .原来有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();


generators发电机

ES6 has generators . ES6 有生成器 You might know them from python .您可能从python认识它们。

They provide asynchronity as well, as they yield new values once they are computed.它们也提供了异步性,因为它们一旦被计算就会yield新的值。

I recommend reading Learn ES2015 for more information on that.我建议阅读Learn ES2015以获取更多信息。

My personal opinion is to never ever use generators as they interfere heavily with promises and make debugging really hard.我个人的观点是永远不要使用生成器,因为它们会严重干扰 Promise 并使调试变得非常困难。


async/await异步/等待

ES7 will make life a whole lot easier with async / await . ES7 将通过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. ES7 异步函数是一个很好的开始阅读。 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(); })();

I have tried to provide a better version of @Dominik Schreiber's answer我试图提供更好版本的@Dominik Schreiber 的答案

 async function callee() { return new Promise((resolve, reject) => { setTimeout(() => resolve('finished!'), 1000); }) } async function caller() { console.log('started!'); console.log(await callee()); } caller();

You can add a callback to the event que with您可以使用以下命令向事件 que 添加回调

 process.nextTick(callback);

Don't do that, it is almost never what you want.不要那样做,这几乎永远不是你想要的。 JavaScript is single threaded so adding a callback still blocks the call of f2. JavaScript 是单线程的,因此添加回调仍然会阻止 f2 的调用。 If you have a function that takes a long time to run run it in a child_process or even better, create a separate micro service for it.如果你有一个函数需要很长时间才能在 child_process 中运行它,甚至更好,请为其创建一个单独的微服务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM