Book Image

Learning Node.js for .NET Developers

Book Image

Learning Node.js for .NET Developers

Overview of this book

Node.js is an open source, cross-platform runtime environment that allows you to use JavaScript to develop server-side web applications. This short guide will help you develop applications using JavaScript and Node.js, leverage your existing programming skills from .NET or Java, and make the most of these other platforms through understanding the Node.js programming model. You will learn how to build web applications and APIs in Node, discover packages in the Node.js ecosystem, test and deploy your Node.js code, and more. Finally, you will discover how to integrate Node.js and .NET code.
Table of Contents (21 chapters)
Learning Node.js for .NET Developers
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Using the callback pattern for asynchronous code


Let's look at one of the methods from our games service:

module.exports.get = (id) => games.find(game => game.id === id);

The interface of this function is synchronous: you call it and get a value back. Chapter 4, Introducing Node.js Modules, introduced the games service as the module responsible for how we store our games. The interface shouldn't need to change if we change the storage implementation. This isn't quite the case at the moment, though.

As discussed before, most Node.js libraries are asynchronous. Synchronous interfaces can't make use of asynchronous implementations. Let's say the get function wants to make use of an asynchronous method in a third-party datastore library. What would that look like? The comments in the following (non-working) code describe the problem:

module.exports.get = (id) => {
    datastore.getById(id, (err, result) => {
        // Result available, but outer method has already returned
    });
...