Q
Q
qwerty2018-03-07 20:17:28
JavaScript
qwerty, 2018-03-07 20:17:28

What are your comments on this code? How to write correctly?

Am I reporting errors correctly? How would you write this code?

const http = require('http');

async function getBody(url) {
    return new Promise((resolve, reject) => {
        http.get(url, (res) => {
            if (res.statusCode !== 200) {
                throw new Error('Request Failed.\n' +
                    `Status Code: ${res.statusCode}`);
            }

            res.setEncoding('utf8');
            let rawData = '';

            res.on('data', (chunk) => {
                rawData += chunk;
            });

            res.on('end', () => {
                return resolve(rawData);
            });

        });
    });
}

(async () => {
  try {
    let body = await getBody('http://site.com/');
    console.log(body);
  } catch (err) {
    console.error(err);
  }
})();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vitaly, 2018-03-07
@vshvydky

Resolve without return, instead of reject, write New Error
Getbody into it without async, you return a promise from a regular function

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question