khex
khex

Reputation: 2828

Sequence of operation in Node.js

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");

Upvotes: 0

Views: 3006

Answers (1)

Poni
Poni

Reputation: 11317

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");
});

Upvotes: 2

Related Questions