Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've completed this exercise from learnyounode and I'm trying to refactor it using ES2015's promises (or with other libraries if it's easier). I've read about promises and I think I understand how they work, but I'd like to know if it's possible to use them in the following code and how to do it.

My goal is to make the code easier to read and understand, and also better understand promises in the process.

let http = require("http");

if (process.argv.length != 5) {
    throw new Error("Please provide the 3 URLs as a command line arguments");
}

let urls = [];
let results = [];
let count = 0;

for (let i = 2; i <  process.argv.length; i++) {
    urls.push(process.argv[i]);
}

function httpGet(index) {
    let url = urls[index];
    let result = "";

    http.get(url, res => {
        res.on("data", data => {
            result += data;
        });

        res.on('end', () => {
            count += 1;
            results[index] = result;

            if (count === 3) {
                results.forEach(function(result) {
                   console.log(result);
                });
            }
        });
    });

}

for (let i = 0; i < urls.length; i++) {
    httpGet(i);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
380 views
Welcome To Ask or Share your Answers For Others

1 Answer

You could try something like this:

'use strict';

const http = require('http');
if (process.argv.length != 5) {
    throw new Error('Please provide the 3 URLs as a command line arguments');
}

let urls = [];
for (let i = 2; i <  process.argv.length; i++) {
    urls.push(process.argv[i]);
}

function httpGet(url) {
    let result = '';
    return new Promise((resolve, reject) => {
        http.get(url, function (res) {
            res.on('error', err => {
                reject(err);
            });
            res.on('data', data => {
                result += data;
            });
            res.on('end', () => {
                //You can do resolve(result) if you don't need the url.
                resolve({url, result});
            });
        })
    });
}

let promises = urls.map(url => httpGet(url));

Promise.all(promises)
    .then(results => {
        console.log(`All done. Results: ${results}`);
    })
    .catch(err => {
        console.error(err);
    });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...