R
R
Robot Chappie2016-09-06 17:44:46
JavaScript
Robot Chappie, 2016-09-06 17:44:46

How to work with asynchronous code?

There is code that adds data to an array through a loop.

const dns = require('dns');

var arr = [];

function resolve(hostname, rrtype) {
    for (var i = 0; i < rrtype.length; i++) {
        dns.resolve(hostname, rrtype[i], (err, data) => { 
            if (!err) {
                arr.push(data)
                console.log(i)
            } else {
                console.log(err);
            };
        });
    };
}

resolve('google.com', ['A', 'MX', 'NS', 'TXT']);
console.log(arr);

If we call console.log(arr);, then an empty array is output because the function has not finished executing yet. What is the most correct way to display the contents of the array, only after the function has been executed. What are the general ways? Because I always have to write a rake to achieve this, I would like to clarify with you how you would act in this situation and what methods are correct and more effective? I will be grateful for any answers. Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Belyaev, 2016-09-06
@BenderLib

Promise

const dns = require('dns');

function resolve(hostname, rrtype) {
    return Promise.all(rrtype.map(rrt => resolveInternal(hostname, rrt)));
}

function resolveInternal(hostname, rrtype) {
    return new Promise((resolve, reject) => {
        dns.resolve(hostname, rrtype, (err, data) => { 
            if (err) {
                reject(err);
                return;
            }
            resolve(data);
        });
    });
}

resolve('google.com', ['A', 'MX', 'NS', 'TXT']).then(arr => console.log(arr));

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question