简体   繁体   中英

Node.js / Express.js - Should I Wrap All My Functions Inside A New Promise?

Express documentation Production best practices: performance and reliability says:

Don't use synchronous functions

Synchronous functions and methods tie up the executing process until they return. A single call to a synchronous function might return in a few microseconds or milliseconds, however in high-traffic websites, these calls add up and reduce the performance of the app. Avoid their use in production.

So my question is, in the context of node/express, if I have a function that accepts some static value and returns a calculated result (what I would normally consider a "synchronous function"), is it best practice to wrap that function inside a new Promise and resolve the result or does this create any significant unnecessary overhead? For example:

Current:

//inside my index.js
var myArgument = 'some long string';
var myResult = myFunction(myArgument);

function myFunction(myArgument){
  var thisResult;
  //some calculations
  return thisResult;
}

New (and Improved?)

//inside my index.js
(async function() {
var myArgument = 'some long string';
var myResult = await myFunction(myArgument);
});

function myFunction(url) {
  return new Promise((resolve, reject) => {
    var thisResult;
    //some calculations
    if(thisResult){
      resolve (thisResult);
    } else {
      reject (null)
    }
  });
}

Short answer: Nope.

The documentation is talking about not using synchronous versions of functions like readfileSync from nodeJS filesystem or bcrypt.compareSync for example. Synchronous calls block the event loop in nodeJS. So nothing happens while you are waiting for the synchronous call to finish. The whole program is on halt while this one method finishes. This is bad in a single threaded system like nodeJS.

There no reason to wrap functions that are just simple calculations or array manipulations with callbacks or promises.

Its just saying that if there's a library/method that offers synchronous version of the method, try to avoid that method.

Check out: https://nodejs.org/en/docs/guides/blocking-vs-non-blocking/

JavaScript execution in Node.js is single threaded, so concurrency refers to the event loop's capacity to execute JavaScript callback functions after completing other work. Any code that is expected to run in a concurrent manner must allow the event loop to continue running as non-JavaScript operations, like I/O, are occurring.

As an example, let's consider a case where each request to a web server takes 50ms to complete and 45ms of that 50ms is database I/O that can be done asynchronously. Choosing non-blocking asynchronous operations frees up that 45ms per request to handle other requests. This is a significant difference in capacity just by choosing to use non-blocking methods instead of blocking methods.

The event loop is different than models in many other languages where additional threads may be created to handle concurrent work.

Regarding additional overhead with wrapping everything in promises. The answer is still no.

You will experience no difference in

function sum(x,y) {
  return x+y
}

const ans = sum(1,2)
console.log(ans) // 3

and

function sum(x,y) {
 return Promise.resolve(x+y) // Shorthand for your new Promise
}

sum(1,2).then(ans => {
  console.log(ans) //3
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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