I am finding way out to use async / await with https post. Please help me out. I have posted my https post code snippet below.how do I use async await with this.
const https = require('https') const data = JSON.stringify({ todo: 'Buy the milk' }) const options = { hostname: 'flaviocopes.com', port: 443, path: '/todos', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': data.length } } const req = https.request(options, (res) => { console.log(`statusCode: ${res.statusCode}`) res.on('data', (d) => { process.stdout.write(d) }) }) req.on('error', (error) => { console.error(error) }) req.write(data) req.end()
Using Javascript Promises to Make HTTP RequestThe request is sent to the server asynchronously, and the response is collected asynchronously.
const https = require('https') async function fetch(url) { return new Promise((resolve, reject) => { const request = https. get(url, { timeout: 1000 }, (res) => { if (res. statusCode < 200 || res. statusCode > 299) { return reject(new Error(`HTTP status code ${res.
To use async and await with Axios in React, we can call axios in an async function. We call axios with the URL we want to make a GET request to. It returns a promise that resolves to an object with the data property set to the response data. So we use await to return the resolved value from the promise.
Axios is a promise based HTTP client for the browser and Node. js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.
Basically, you can write a function which will return a Promise
and then you can use async
/await
with that function. Please see below:
const https = require('https') const data = JSON.stringify({ todo: 'Buy the milk' }); const options = { hostname: 'flaviocopes.com', port: 443, path: '/todos', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': data.length }, }; async function doSomethingUseful() { // return the response return await doRequest(options, data); } /** * Do a request with options provided. * * @param {Object} options * @param {Object} data * @return {Promise} a promise of request */ function doRequest(options, data) { return new Promise((resolve, reject) => { const req = https.request(options, (res) => { res.setEncoding('utf8'); let responseBody = ''; res.on('data', (chunk) => { responseBody += chunk; }); res.on('end', () => { resolve(JSON.parse(responseBody)); }); }); req.on('error', (err) => { reject(err); }); req.write(data) req.end(); }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With