NodeJS Async function help!

Discussion in 'Coding, Scripting & Programming' started by Munzy, Dec 8, 2015.

  1. Munzy

    Munzy Active Member

    432
    205
    Aug 13, 2014
    Alright, so I am new to nodejs from php. As most know, php being linear/blocking made coding *easy* per-say. However, I have found myself loving nodejs, and I am having a hard time wrapping my mind around how to let a nodejs function run async, but then wait for responses of that async function before continuing.


    Here is some example code


    var ping = require("ping");

    var verHosts = [
    '192.168.230.118',
    '192.168.230.25'
    ];

    var verStatus = 0;

    verHosts.forEach(function(host) {
    ping.sys.probe(host, function(isAlive){
    if(isAlive == true) {
    verStatus++;
    }
    })
    });
    console.log(Date() + " " + "Verified status is at: " + verStatus);
    if(verStatus > 0) { // continue shiz and giggles here after I get the above};




    If you could elaborate as I am trying to learn as well, not just copy paste in dummy mode!


    Thanks!
     
    Last edited by a moderator: Dec 8, 2015
  2. joepie91

    joepie91 New Member

    459
    328
    Jun 19, 2013
    Basically, you'd use Promises. Any kind of looping or conditional asynchronous work is very hard to get right with callbacks alone.


    I've put together a reading list about Promises here, that should get you started - Promise.map is most likely what you're looking for in particular :)
     
    Last edited by a moderator: Dec 12, 2015