Using promises instead of error first callbacks

Now, let's start considering several techniques that will come in handy when writing services.

Node runs as a single thread, so if every time it had to call a service, or read a file, or access a database, or do any other I/O-related operation, it would have to wait for it to finish, then attending requests would take a long time, blocking other requests from being attended, and the server would show a very bad performance. Instead, all operations such as those are always done asynchronically, and you must provide a callback that will be called whenever the operation is finished; meanwhile, Node will be available to process other clients' requests.

There are synchronous versions of many functions, but they can only be applied for desktop work, and never for web servers.

Node established a standard that all callbacks should receive two parameters: an error and a result. If the operation failed somehow, the error argument would describe the reason. Otherwise, if the operation had succeeded, the error would be null or undefined (but, in any case, a falsy value) and the result would have the resultant value.

This means that the usual Node code is full of callbacks, and if a callback itself needs another operation, that means yet more callbacks, which themselves may have even more callbacks, resulting in what is called callback hell. Instead of working in this fashion, we want to be able to opt for modern promises, and, fortunately, there is a simple way to do so. Let's see how we can simplify our code by avoiding callbacks.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.168.163