Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Sequence of operation in Node.js

Sequence of operation in Node.js

Problem

I took the example code from npmjs > jsdom. This process is performed in a few seconds and only after it I want to run a second action, such as console.log. But do not insert the code in the body of jsdom. Maybe it's work with Node.js > Stream Whant to create a chain of functions, next process start as soon as the end of the previous.

Where i can read about sequence in Node.js?

var jsdom = require("jsdom");

jsdom.env({
  url: "http://news.ycombinator.com/",
  scripts: ["http://code.jquery.com/jquery.js"],
  done: function (errors, window) {
    var $ = window.$;
    console.log("HN Links");
    $("td.title:not(:last) a").each(function() {
      console.log(" -", $(this).text());
    });
  }
});

console.log("The end");
Problem courtesy of: khex

Solution

You're looking for Async.js.

To be specific, you're looking for its series() functionality (Run an array of functions in series, each one running once the previous function has completed).

Code example (based on it's docs):

async.series([
    function(callback){
        jsdom.env({
  url: "http://news.ycombinator.com/",
  scripts: ["http://code.jquery.com/jquery.js"],
  done: function (errors, window) {
    var $ = window.$;
    console.log("HN Links");
    $("td.title:not(:last) a").each(function() {
      console.log(" -", $(this).text());
    });
callback(null, 'one');
  }
});
    },
    function(callback){
        // do some more stuff (second task) ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results){
    console.log("The end");
});
Solution courtesy of: Poni

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Sequence of operation in Node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×