How to Write Asynchronous Functions for Node.Js

Writing custom, true Asynchronous functions in Javascript/Node

Just a side note, true asynchronous doesn't really mean anything. But we can assume you mean parallelism?.

Now depending on what your doing, you might find there is little to no benefit in using threads in node. Take for example: nodes file system, as long as you don't use the sync versions, it's going to automatically run multiple requests in parallel, because node is just going to pass these requests to worker threads.

It's the reason when people say Node is single threaded, it's actually incorrect, it's just the JS engine that is. You can even prove this by looking at the number of threads a nodeJs process takes using your process monitor of choice.

So then you might ask, so why do we have worker threads in node?. Well the V8 JS engine that node uses is pretty fast these days, so lets say you wanted to calculate PI to a million digits using JS, you could do this in the main thread without blocking. But it would be a shame not to use those extra CPU cores that modern PC's have and keep the main thread doing other things while PI is been calculated inside another thread.

So what about File IO in node, would this benefit been in a worker thread?.. Well this depends on what you do with the result of the file-io, if you was just reading and then writing blocks of data, then no there would be no benefit, but if say you was reading a file and then doing some heavy calculations on these files with Javascript (eg. some custom image compression etc), then again a worker thread would help.

So in a nutshell, worker threads are great when you need to use Javascript for some heavy calculations, using them for just simple IO may in fact slow things down, due to IPC overheads.

You don't mention in your question what your trying to run in parallel, so it's hard to say if doing so would be of benefit.

How to write asynchronous functions for Node.js

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.

How do I write asynchronous functions for Node?

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

How should I implement error event handling correctly

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

Edit:

var async_function = function(val, callback){
process.nextTick(function(){
callback(val);
});
};

The above function when called as

async_function(42, function(val) {
console.log(val)
});
console.log(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.

Preferred way to write async function in a Node.js SDK

The modern asynchronous API design in Javascript is to return a promise that resolves or rejects when your asynchronous operation is completed because promises make it easier to manage asynchronous code and error flow than plain callbacks, particularly when there are sequences of asynchronous operations in the code flow.

Most newly designed nodejs APIs are designed with a promise interface and most older callback-style interfaces in nodejs are adding an option for a promise interface. The move to promises is clearly a trend in Javascript asynchronous programming in general and definitely for nodejs.

This allows the caller to then use async/await or .then().catch() - their choice.

Note your API design does not "go with" async/await in particular. That's up to the caller. If you return a promise from your API, then the caller may choose to use async/await or .then().catch() if they want.

Node.js - How do you call an async function with a callback?

Please use the async await

I have written a test code for you as below:

const express = require('express');
const app = express();
const dns = require('dns');

let CheckUrl = function (url, done) {
return new Promise((resolve, reject) => {
dns.lookup(url, function(err, address) {
console.log("err " , err)
if (err) {
resolve(false)
} else {
resolve(true)
}

});
});
}

app.post("/api/shorturl/new", async function(req, res) {

try {

let result = await CheckUrl(req.body.url);
console.log("result " , result)
res.send(result)
}
catch (error) {
console.log("in catch error " , error)
res.send(error)
}
});

app.listen(3000)

you can get the knowledge to know about the Promise here. The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

NodeJs - Writing async and non-async functions together

You need to return something from checkSystemData()

return (async () => { // add return
let sd = await systemData()
if (sd.manufacturer === 'X') { // Many more such checks

} else {
return { check: false, manufacturer: sd.manufacturer }
}
})()

then you can use

checkSystemData().then(response => {
console.log(response)
})

or

let x = await checkSystemData()


Related Topics



Leave a reply



Submit