Reputation: 2356
I have some functions that do a lot of calculations with data and arrays but all in memory, it does not do any IO. I've been reading trying to get into nodejs, I was wondering if there is any benefit on making then async? For example, function a
:
function a(b, c, d) {
// a lot of operations with arrays
return value;
}
Does it make any sense to return a promise in this case if it does not involve any IO blocking operation? For example:
function a(b, c, d) {
return new Promise(resolve, reject) {
// a lot of operations with arrays
resolve(value);
}
}
Is there any improvement in using promises in this case or am I only overcomplicating this and should just return the value and not a promise?
Upvotes: 1
Views: 757
Reputation: 1
You can do the lot of operations with arrays
in "batches" to avoid "blocking" other execution - the following is "pseudo" code in that you haven't shown what // a lot of operations with arrays
actually is ... so
function a(b, c, d) {
return new Promise((resolve, reject) => {
function processBatch() {
// do some operations with arrays
if (error) {
reject(error);
} else if (needToProcessMore) {
setImmediate(processBatch);
} else {
resolve(someResult);
}
}
setImmediate(processBatch);
});
}
Alternatively, (though I've never used them myself) there are "thread" and "thread worker" type libraries available for node
Upvotes: 1
Reputation: 370789
No, async functions are only syntax sugar on top of promises. If your function doesn't actually have any asynchronous operations (like a network request), it will keep executing synchronously and will resolve synchronously, so it'll be no different from an ordinary function.
Javascript is single-threaded.
Upvotes: 4