javascript - how to create a custom asynchronous function in node.js -
ii'm trying 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 , got output expected.
but, want call function fun1()
, fun2()
asynchronously means fun2()
call before fun1()
, b'coz fun1()
take time complete execution compare fun2()
.
how can achieve this, node.js provide asynchronous function, defined function can asynchronous or can make them according our need.
there multiple ways achieve in javascript (not node-specific, there modules make life easier):
callbacks
they continuations , shame developers bothered handling them manually (compilers used themselves). work:
function callee(callback) { settimeout(function() { callback(null, 'finished!'); }, 2000); } function caller() { document.write('started!'); callee(function(err, result) { document.write(result); }); } caller();
it common in node environment indicate errors first parameter of callback (like callback(new error("something wrong!"))
).
promises
as callbacks ugly when nested (imagine 10-20 of them, you'd screwed debugging this), idea of promises came up. might know them futures java. built-in es6, , can use them beforehand in node environment npm promise
-- many client-side frameworks (e.g. jquery, angularjs) have own implementations. there 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. might know them python.
they provide asynchronity well, yield
new values once computed.
i recommend reading learn es2015 more information on that.
my personal opinion never ever use generators interfere heavily promises , make debugging hard.
async/await
es7 make life whole lot easier async
/await
. can function performed asynchronously , want await result (once in async function). es7 async functions start 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()); } // global async wrapper (async function() { caller(); })();
Comments
Post a Comment