Using the http Module with Promises

Node.js 10 introduced improvements to the http module, making it easier to work with HTTP requests and responses.

javascriptCopy code// Example using http module with async/await
const http = require('http');

function request(url) {
return new Promise((resolve, reject) => {
    http.get(url, (response) => {
        let data = '';
        response.on('data', (chunk) => data += chunk);
        response.on('end', () => resolve(data));
    }).on('error', reject);
});
} async function fetchData() {
try {
    const data = await request('http://www.example.com');
    console.log(data);
} catch (err) {
    console.error('Error fetching data:', err);
}
} fetchData();

Explanation:

  • Wrap the http.get function in a Promise to use with async/await.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *