Giter Club home page Giter Club logo

node-api-promises's Introduction

General Assembly Logo

Using Promises with the Node API

Prerequisites

Objectives

By the end of this, developers should be able to:

  • Explain the value of using promises instead of callback interfaces.
  • Read Node documentation that uses callbacks and translate that into implementations using promises.
  • Convert Node scripts using callbacks into scripts using promises.

Preparation

  1. Fork and clone this repository.
  2. Install dependencies with npm install.

Callbacks versus Promises

Callback drawbacks:

  • Callbacks can be messy when they're nested: "callback hell". See lib/copy-json.js.
  • Each callback will have to handle it's own errors if necessary.
  • In complex programs, it will be hard to tell in what order callbacks fire.

Pros for Promises:

  • Promises, like callbacks, make asynchronicity explict.
  • Promises, unlike callbacks, have a predictable order of execution.
  • Promises are easier to read than callbacks.
  • Promises can simplify error handling.

Lab: Research the Promises API

Take a few minutes to read the following API documentation for the native Promises.

Note function signatures and argument types as you read. What kind of object does a promise take when it is constructed?

  1. Promise Syntax
  2. Promise.prototype

Read-Along: Using Promises Instead of Callbacks

// remember that callback is something you write, in this case to perform some
// processing on parsed JSON
let readJSON = function (filename, callback){
  fs.readFile(filename, 'utf8', function (err, res){
    if (err) return callback(err); // what's going on here?
    callback(null, JSON.parse(res)); // what if JSON.parse errors out?
  });
};

What are some weaknesses in this code? And the following?

let readJSON = function (filename, callback){ // ๐Ÿ‘€ here
  fs.readFile(filename, 'utf8', function (err, res){
    if (err) return callback(err); // pass the error from readFile
    try {
      res = JSON.parse(res);
    } catch (ex) {
      return callback(ex); // pass the error from JSON.parse
    }
    callback(null, res); // don't pass the error, since we should have caught it
  });
};

What about this instead?

let readJSON = function (filename){ // ๐Ÿ‘€ here
  return new Promise((resolve, reject) => {
    fs.readFile(filename, 'utf8', (err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  }).then((res) => {
    return JSON.parse(res)
  }).catch((err) => {
    console.log(err);
  });
};

That's too verbose. This is better:

let readJSON = function (filename){
  return new Promise((resolve, reject) => {
    fs.readFile(filename, 'utf8', (err, res) => {
      if (err) {
        reject(err);
      } else {
        resolve(res);
      }
    });
  }).then(JSON.parse).catch(console.log); // what can we surmise about .then?
};

Code-Along: Promisify copy-json.js

Lab: Pomisify hey-yall.js

Lab: Promisify randomizer.js

Additional Resources

Source code distributed under the MIT license. Text and other assets copyright General Assembly, Inc., all rights reserved.

node-api-promises's People

Watchers

Jeremiah Damiron avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.