使用承诺而不是回调 [英] Use promises instead of callbacks

查看:72
本文介绍了使用承诺而不是回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经从 learnyounode 完成了本练习,并且我正在尝试使用ES2015的promises重构它(如果更容易的话,可以使用其他库)。我已经读过关于承诺的书,我想我了解它们的工作原理,但是我想知道是否有可能在以下代码中使用它们以及如何实现它们。

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


推荐答案

您可以尝试类似的方法:

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

这篇关于使用承诺而不是回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆