Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use async await with https post request

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() 
like image 628
Dhiraj Bastwade Avatar asked Oct 23 '18 14:10

Dhiraj Bastwade


People also ask

Is https request asynchronous?

Using Javascript Promises to Make HTTP RequestThe request is sent to the server asynchronously, and the response is collected asynchronously.

How do you get a response from async method in node JS?

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.

Can I use async await with Axios?

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.

Is Axios get async?

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.


1 Answers

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();   }); } 
like image 56
Rishikesh Darandale Avatar answered Sep 23 '22 10:09

Rishikesh Darandale