Skip to content

Instantly share code, notes, and snippets.

@jimyang2008
Last active July 8, 2020 03:22
Show Gist options
  • Save jimyang2008/764087d6e7617ae54e634ca4abb6fe7d to your computer and use it in GitHub Desktop.
Save jimyang2008/764087d6e7617ae54e634ca4abb6fe7d to your computer and use it in GitHub Desktop.
NodeJS study notes

Node JS characteristics

Functional programming

Asynchronous programming

Tasks can be executed asynchronously only if NO dependency.

With dependency, there will be a producer and a consumer. Consumer need to process result provided by producer. There are several ways to achieve this from history.

  • callbacks : producer is defined with a function on what to do after
  • Promise : producer returns an object with what to do after
  • async/await :

Callbacks : pyramid of doom, top-level step functions

  • producer logic defined with a callback for consumer to hook in
  • consumer logic defined in callback and passed to producer
# producer
function producer( args, callback ) {
    try {
        result = take_time_to_get_result()
        callback(null, result)
    } catch (err) {
        callback(err)
    }
}

# consumer
function consumer(producer) {
  producer(args, function(err, result) {
      if (err) {
          handle_error(err)
      } else {
          consume(result)
      }
  })
}

Promise : 1-to-n producer/consumer handling

  • producer logic is encapsulated in Promise and executed upon creation
  • consumer logic is defined and passed to Promise object, not as callback to producer
  • consumers can be added in dynamically
# producer
function producer(args) {
  function executor(resolve, reject) {
    try {
      value = take_time_to_get_result()
      resolve(value)
    } catch (err) {
      reject(err)
    }
  }
  return new Promise( executor );
};

# consumer
function consumer() {
  let promise = producer(args)
  promise.then(result_handler(result), error_handler(error));
}
state result
pending undefined
fulfilled value
rejected error

async/await

  • async function always returns a promise
  • await (must inside async function) makes the script wait until promise settles and returns
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment