Executing functions in order











up vote
-1
down vote

favorite












Basically, I'm making a small script to check the IP of some servers based on their hostname, then compare that IP to a list based on the IP block a router is issuing.



The problem I'm having is clearly with the code executing asynchronously, and it's likely been answered a thousand times, but I can't seem to wrap my head around how to fix it. I've tried wrapping everything in promises but I end up breaking everything. Here is the latest attempt to break the steps I need out into individual functions.



const dns = require('dns');
const Table = require('cli-table');
const hosts = ['Server01', 'Server02', 'Server03'];
let list = ;

table = new Table({
head: ['Host', 'Location']
, colWidths: [20, 30]
});

function process() {
hosts.forEach(host => {
dns.lookup(host, function (err, result) {
ipSplit = result.split(".");
r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
if (r == '10.23.13') {
list.push([host, 'Lab A112']);
}
else {
list.push([host, 'Unknown']);
}
});
});
};

function build () {
table.push(list);
};

function push () {
console.log(table.toString());
};

process();
build();
push();


What piece of the puzzle am I missing here?










share|improve this question






















  • Promise.all. Use Promise.all
    – Jared Smith
    Nov 20 at 16:51















up vote
-1
down vote

favorite












Basically, I'm making a small script to check the IP of some servers based on their hostname, then compare that IP to a list based on the IP block a router is issuing.



The problem I'm having is clearly with the code executing asynchronously, and it's likely been answered a thousand times, but I can't seem to wrap my head around how to fix it. I've tried wrapping everything in promises but I end up breaking everything. Here is the latest attempt to break the steps I need out into individual functions.



const dns = require('dns');
const Table = require('cli-table');
const hosts = ['Server01', 'Server02', 'Server03'];
let list = ;

table = new Table({
head: ['Host', 'Location']
, colWidths: [20, 30]
});

function process() {
hosts.forEach(host => {
dns.lookup(host, function (err, result) {
ipSplit = result.split(".");
r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
if (r == '10.23.13') {
list.push([host, 'Lab A112']);
}
else {
list.push([host, 'Unknown']);
}
});
});
};

function build () {
table.push(list);
};

function push () {
console.log(table.toString());
};

process();
build();
push();


What piece of the puzzle am I missing here?










share|improve this question






















  • Promise.all. Use Promise.all
    – Jared Smith
    Nov 20 at 16:51













up vote
-1
down vote

favorite









up vote
-1
down vote

favorite











Basically, I'm making a small script to check the IP of some servers based on their hostname, then compare that IP to a list based on the IP block a router is issuing.



The problem I'm having is clearly with the code executing asynchronously, and it's likely been answered a thousand times, but I can't seem to wrap my head around how to fix it. I've tried wrapping everything in promises but I end up breaking everything. Here is the latest attempt to break the steps I need out into individual functions.



const dns = require('dns');
const Table = require('cli-table');
const hosts = ['Server01', 'Server02', 'Server03'];
let list = ;

table = new Table({
head: ['Host', 'Location']
, colWidths: [20, 30]
});

function process() {
hosts.forEach(host => {
dns.lookup(host, function (err, result) {
ipSplit = result.split(".");
r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
if (r == '10.23.13') {
list.push([host, 'Lab A112']);
}
else {
list.push([host, 'Unknown']);
}
});
});
};

function build () {
table.push(list);
};

function push () {
console.log(table.toString());
};

process();
build();
push();


What piece of the puzzle am I missing here?










share|improve this question













Basically, I'm making a small script to check the IP of some servers based on their hostname, then compare that IP to a list based on the IP block a router is issuing.



The problem I'm having is clearly with the code executing asynchronously, and it's likely been answered a thousand times, but I can't seem to wrap my head around how to fix it. I've tried wrapping everything in promises but I end up breaking everything. Here is the latest attempt to break the steps I need out into individual functions.



const dns = require('dns');
const Table = require('cli-table');
const hosts = ['Server01', 'Server02', 'Server03'];
let list = ;

table = new Table({
head: ['Host', 'Location']
, colWidths: [20, 30]
});

function process() {
hosts.forEach(host => {
dns.lookup(host, function (err, result) {
ipSplit = result.split(".");
r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
if (r == '10.23.13') {
list.push([host, 'Lab A112']);
}
else {
list.push([host, 'Unknown']);
}
});
});
};

function build () {
table.push(list);
};

function push () {
console.log(table.toString());
};

process();
build();
push();


What piece of the puzzle am I missing here?







javascript node.js






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 at 16:43









TheMean Won

375




375












  • Promise.all. Use Promise.all
    – Jared Smith
    Nov 20 at 16:51


















  • Promise.all. Use Promise.all
    – Jared Smith
    Nov 20 at 16:51
















Promise.all. Use Promise.all
– Jared Smith
Nov 20 at 16:51




Promise.all. Use Promise.all
– Jared Smith
Nov 20 at 16:51












2 Answers
2






active

oldest

votes

















up vote
0
down vote













You'll want to use Promise.all:



const result = Promise.all(hosts.map(host => {
return new Promise((resolve, reject) => {
dns.lookup(host, function (err, result) {
if (err) reject(err);
const ipSplit = result.split(".");
const r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
if (r === '10.23.13') {
resolve([host, 'Lab A112']);
} else {
resolve([host, 'Unknown']);
}
});
}
}));





share|improve this answer




























    up vote
    0
    down vote













    You can order your function calls with async/await and you will get the order you need.



    const dns = require('dns');
    const Table = require('cli-table');
    const hosts = ['Server01', 'Server02', 'Server03'];
    let list = ;

    table = new Table({
    head: ['Host', 'Location']
    , colWidths: [20, 30]
    });

    function process() {
    return new Promise((resolve, reject) => {
    hosts.forEach(host => {
    dns.lookup(host, function (err, result) {
    ipSplit = result.split(".");
    r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
    if (r == '10.23.13') {
    resolve(list.push([host, 'Lab A112']));
    }
    else {
    reject(list.push([host, 'Unknown']));
    }
    });
    });
    })
    };

    function build () {
    return new Promise((resolve, reject)=>{
    resolve(table.push(list);)
    })

    };

    function push () {
    console.log(table.toString());
    };
    async function waitForFunctions() {
    try{
    const resOne = await process();
    const resTwo = await build()
    } catch(error){
    console.log(error);
    }
    return Promise.all([resOne, resTwo])
    }
    waitForFunctions()
    .then((values)=>{
    console.log(values);
    console.log(push());
    });





    share|improve this answer





















    • A little over complicated. the build function is synchronous by nature. You've crafted a answer to support a solution rather than a solution to support the question.
      – Randy Casburn
      Nov 20 at 17:12










    • @RandyCasburn This is just how I interpret the problem and how I would have solved it. Yes, build is sync, but I need to make sure that it is not called before process function has finished, so I turn it into promise.
      – squeekyDave
      Nov 20 at 17:15










    • Fair enough. But that is already ensured with `process().then(()=>{build();push()}); This is much, much simpler and easier to comprehend.
      – Randy Casburn
      Nov 20 at 17:18










    • @RandyCasburn the process function does not return anything from the original example, but yeas, there is definetally a shorter way to achieve the same thing, just async/awit for me is the simpler thing, but thats just me.
      – squeekyDave
      Nov 20 at 17:22






    • 1




      I meant you still need your promise returned from process() for sure. Didn't mean to be obscure. All good. Get your intent.
      – Randy Casburn
      Nov 20 at 17:24











    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397647%2fexecuting-functions-in-order%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    0
    down vote













    You'll want to use Promise.all:



    const result = Promise.all(hosts.map(host => {
    return new Promise((resolve, reject) => {
    dns.lookup(host, function (err, result) {
    if (err) reject(err);
    const ipSplit = result.split(".");
    const r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
    if (r === '10.23.13') {
    resolve([host, 'Lab A112']);
    } else {
    resolve([host, 'Unknown']);
    }
    });
    }
    }));





    share|improve this answer

























      up vote
      0
      down vote













      You'll want to use Promise.all:



      const result = Promise.all(hosts.map(host => {
      return new Promise((resolve, reject) => {
      dns.lookup(host, function (err, result) {
      if (err) reject(err);
      const ipSplit = result.split(".");
      const r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
      if (r === '10.23.13') {
      resolve([host, 'Lab A112']);
      } else {
      resolve([host, 'Unknown']);
      }
      });
      }
      }));





      share|improve this answer























        up vote
        0
        down vote










        up vote
        0
        down vote









        You'll want to use Promise.all:



        const result = Promise.all(hosts.map(host => {
        return new Promise((resolve, reject) => {
        dns.lookup(host, function (err, result) {
        if (err) reject(err);
        const ipSplit = result.split(".");
        const r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
        if (r === '10.23.13') {
        resolve([host, 'Lab A112']);
        } else {
        resolve([host, 'Unknown']);
        }
        });
        }
        }));





        share|improve this answer












        You'll want to use Promise.all:



        const result = Promise.all(hosts.map(host => {
        return new Promise((resolve, reject) => {
        dns.lookup(host, function (err, result) {
        if (err) reject(err);
        const ipSplit = result.split(".");
        const r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
        if (r === '10.23.13') {
        resolve([host, 'Lab A112']);
        } else {
        resolve([host, 'Unknown']);
        }
        });
        }
        }));






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 20 at 16:53









        Jared Smith

        9,16031843




        9,16031843
























            up vote
            0
            down vote













            You can order your function calls with async/await and you will get the order you need.



            const dns = require('dns');
            const Table = require('cli-table');
            const hosts = ['Server01', 'Server02', 'Server03'];
            let list = ;

            table = new Table({
            head: ['Host', 'Location']
            , colWidths: [20, 30]
            });

            function process() {
            return new Promise((resolve, reject) => {
            hosts.forEach(host => {
            dns.lookup(host, function (err, result) {
            ipSplit = result.split(".");
            r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
            if (r == '10.23.13') {
            resolve(list.push([host, 'Lab A112']));
            }
            else {
            reject(list.push([host, 'Unknown']));
            }
            });
            });
            })
            };

            function build () {
            return new Promise((resolve, reject)=>{
            resolve(table.push(list);)
            })

            };

            function push () {
            console.log(table.toString());
            };
            async function waitForFunctions() {
            try{
            const resOne = await process();
            const resTwo = await build()
            } catch(error){
            console.log(error);
            }
            return Promise.all([resOne, resTwo])
            }
            waitForFunctions()
            .then((values)=>{
            console.log(values);
            console.log(push());
            });





            share|improve this answer





















            • A little over complicated. the build function is synchronous by nature. You've crafted a answer to support a solution rather than a solution to support the question.
              – Randy Casburn
              Nov 20 at 17:12










            • @RandyCasburn This is just how I interpret the problem and how I would have solved it. Yes, build is sync, but I need to make sure that it is not called before process function has finished, so I turn it into promise.
              – squeekyDave
              Nov 20 at 17:15










            • Fair enough. But that is already ensured with `process().then(()=>{build();push()}); This is much, much simpler and easier to comprehend.
              – Randy Casburn
              Nov 20 at 17:18










            • @RandyCasburn the process function does not return anything from the original example, but yeas, there is definetally a shorter way to achieve the same thing, just async/awit for me is the simpler thing, but thats just me.
              – squeekyDave
              Nov 20 at 17:22






            • 1




              I meant you still need your promise returned from process() for sure. Didn't mean to be obscure. All good. Get your intent.
              – Randy Casburn
              Nov 20 at 17:24















            up vote
            0
            down vote













            You can order your function calls with async/await and you will get the order you need.



            const dns = require('dns');
            const Table = require('cli-table');
            const hosts = ['Server01', 'Server02', 'Server03'];
            let list = ;

            table = new Table({
            head: ['Host', 'Location']
            , colWidths: [20, 30]
            });

            function process() {
            return new Promise((resolve, reject) => {
            hosts.forEach(host => {
            dns.lookup(host, function (err, result) {
            ipSplit = result.split(".");
            r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
            if (r == '10.23.13') {
            resolve(list.push([host, 'Lab A112']));
            }
            else {
            reject(list.push([host, 'Unknown']));
            }
            });
            });
            })
            };

            function build () {
            return new Promise((resolve, reject)=>{
            resolve(table.push(list);)
            })

            };

            function push () {
            console.log(table.toString());
            };
            async function waitForFunctions() {
            try{
            const resOne = await process();
            const resTwo = await build()
            } catch(error){
            console.log(error);
            }
            return Promise.all([resOne, resTwo])
            }
            waitForFunctions()
            .then((values)=>{
            console.log(values);
            console.log(push());
            });





            share|improve this answer





















            • A little over complicated. the build function is synchronous by nature. You've crafted a answer to support a solution rather than a solution to support the question.
              – Randy Casburn
              Nov 20 at 17:12










            • @RandyCasburn This is just how I interpret the problem and how I would have solved it. Yes, build is sync, but I need to make sure that it is not called before process function has finished, so I turn it into promise.
              – squeekyDave
              Nov 20 at 17:15










            • Fair enough. But that is already ensured with `process().then(()=>{build();push()}); This is much, much simpler and easier to comprehend.
              – Randy Casburn
              Nov 20 at 17:18










            • @RandyCasburn the process function does not return anything from the original example, but yeas, there is definetally a shorter way to achieve the same thing, just async/awit for me is the simpler thing, but thats just me.
              – squeekyDave
              Nov 20 at 17:22






            • 1




              I meant you still need your promise returned from process() for sure. Didn't mean to be obscure. All good. Get your intent.
              – Randy Casburn
              Nov 20 at 17:24













            up vote
            0
            down vote










            up vote
            0
            down vote









            You can order your function calls with async/await and you will get the order you need.



            const dns = require('dns');
            const Table = require('cli-table');
            const hosts = ['Server01', 'Server02', 'Server03'];
            let list = ;

            table = new Table({
            head: ['Host', 'Location']
            , colWidths: [20, 30]
            });

            function process() {
            return new Promise((resolve, reject) => {
            hosts.forEach(host => {
            dns.lookup(host, function (err, result) {
            ipSplit = result.split(".");
            r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
            if (r == '10.23.13') {
            resolve(list.push([host, 'Lab A112']));
            }
            else {
            reject(list.push([host, 'Unknown']));
            }
            });
            });
            })
            };

            function build () {
            return new Promise((resolve, reject)=>{
            resolve(table.push(list);)
            })

            };

            function push () {
            console.log(table.toString());
            };
            async function waitForFunctions() {
            try{
            const resOne = await process();
            const resTwo = await build()
            } catch(error){
            console.log(error);
            }
            return Promise.all([resOne, resTwo])
            }
            waitForFunctions()
            .then((values)=>{
            console.log(values);
            console.log(push());
            });





            share|improve this answer












            You can order your function calls with async/await and you will get the order you need.



            const dns = require('dns');
            const Table = require('cli-table');
            const hosts = ['Server01', 'Server02', 'Server03'];
            let list = ;

            table = new Table({
            head: ['Host', 'Location']
            , colWidths: [20, 30]
            });

            function process() {
            return new Promise((resolve, reject) => {
            hosts.forEach(host => {
            dns.lookup(host, function (err, result) {
            ipSplit = result.split(".");
            r = ipSplit[0] + '.' + ipSplit[1] + '.' + ipSplit[2];
            if (r == '10.23.13') {
            resolve(list.push([host, 'Lab A112']));
            }
            else {
            reject(list.push([host, 'Unknown']));
            }
            });
            });
            })
            };

            function build () {
            return new Promise((resolve, reject)=>{
            resolve(table.push(list);)
            })

            };

            function push () {
            console.log(table.toString());
            };
            async function waitForFunctions() {
            try{
            const resOne = await process();
            const resTwo = await build()
            } catch(error){
            console.log(error);
            }
            return Promise.all([resOne, resTwo])
            }
            waitForFunctions()
            .then((values)=>{
            console.log(values);
            console.log(push());
            });






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 20 at 17:05









            squeekyDave

            369113




            369113












            • A little over complicated. the build function is synchronous by nature. You've crafted a answer to support a solution rather than a solution to support the question.
              – Randy Casburn
              Nov 20 at 17:12










            • @RandyCasburn This is just how I interpret the problem and how I would have solved it. Yes, build is sync, but I need to make sure that it is not called before process function has finished, so I turn it into promise.
              – squeekyDave
              Nov 20 at 17:15










            • Fair enough. But that is already ensured with `process().then(()=>{build();push()}); This is much, much simpler and easier to comprehend.
              – Randy Casburn
              Nov 20 at 17:18










            • @RandyCasburn the process function does not return anything from the original example, but yeas, there is definetally a shorter way to achieve the same thing, just async/awit for me is the simpler thing, but thats just me.
              – squeekyDave
              Nov 20 at 17:22






            • 1




              I meant you still need your promise returned from process() for sure. Didn't mean to be obscure. All good. Get your intent.
              – Randy Casburn
              Nov 20 at 17:24


















            • A little over complicated. the build function is synchronous by nature. You've crafted a answer to support a solution rather than a solution to support the question.
              – Randy Casburn
              Nov 20 at 17:12










            • @RandyCasburn This is just how I interpret the problem and how I would have solved it. Yes, build is sync, but I need to make sure that it is not called before process function has finished, so I turn it into promise.
              – squeekyDave
              Nov 20 at 17:15










            • Fair enough. But that is already ensured with `process().then(()=>{build();push()}); This is much, much simpler and easier to comprehend.
              – Randy Casburn
              Nov 20 at 17:18










            • @RandyCasburn the process function does not return anything from the original example, but yeas, there is definetally a shorter way to achieve the same thing, just async/awit for me is the simpler thing, but thats just me.
              – squeekyDave
              Nov 20 at 17:22






            • 1




              I meant you still need your promise returned from process() for sure. Didn't mean to be obscure. All good. Get your intent.
              – Randy Casburn
              Nov 20 at 17:24
















            A little over complicated. the build function is synchronous by nature. You've crafted a answer to support a solution rather than a solution to support the question.
            – Randy Casburn
            Nov 20 at 17:12




            A little over complicated. the build function is synchronous by nature. You've crafted a answer to support a solution rather than a solution to support the question.
            – Randy Casburn
            Nov 20 at 17:12












            @RandyCasburn This is just how I interpret the problem and how I would have solved it. Yes, build is sync, but I need to make sure that it is not called before process function has finished, so I turn it into promise.
            – squeekyDave
            Nov 20 at 17:15




            @RandyCasburn This is just how I interpret the problem and how I would have solved it. Yes, build is sync, but I need to make sure that it is not called before process function has finished, so I turn it into promise.
            – squeekyDave
            Nov 20 at 17:15












            Fair enough. But that is already ensured with `process().then(()=>{build();push()}); This is much, much simpler and easier to comprehend.
            – Randy Casburn
            Nov 20 at 17:18




            Fair enough. But that is already ensured with `process().then(()=>{build();push()}); This is much, much simpler and easier to comprehend.
            – Randy Casburn
            Nov 20 at 17:18












            @RandyCasburn the process function does not return anything from the original example, but yeas, there is definetally a shorter way to achieve the same thing, just async/awit for me is the simpler thing, but thats just me.
            – squeekyDave
            Nov 20 at 17:22




            @RandyCasburn the process function does not return anything from the original example, but yeas, there is definetally a shorter way to achieve the same thing, just async/awit for me is the simpler thing, but thats just me.
            – squeekyDave
            Nov 20 at 17:22




            1




            1




            I meant you still need your promise returned from process() for sure. Didn't mean to be obscure. All good. Get your intent.
            – Randy Casburn
            Nov 20 at 17:24




            I meant you still need your promise returned from process() for sure. Didn't mean to be obscure. All good. Get your intent.
            – Randy Casburn
            Nov 20 at 17:24


















            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53397647%2fexecuting-functions-in-order%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Feedback on college project

            Futebolista

            Albești (Vaslui)