Dhiraj Bastwade
Dhiraj Bastwade

Reputation: 683

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()

Upvotes: 55

Views: 50844

Answers (3)

David Kaufman
David Kaufman

Reputation: 121

I had this problem also, found this post, and used the solution from Rishikesh Darandale (here).

The await documentation states The await operator is used to wait for a Promise. Returning the promise from a function is not required. You can just create a promise and call await on it.

async function doPostToDoItem(myItem) {

    const https = require('https')

    const data = JSON.stringify({
        todo: myItem
    });

    const options = {
        hostname: 'flaviocopes.com',
        port: 443,
        path: '/todos',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': data.length
        },
    };

    let p = 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();
    });

    return await p;
}

Upvotes: 12

Rishikesh Darandale
Rishikesh Darandale

Reputation: 3310

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

Upvotes: 84

Sanket
Sanket

Reputation: 985

You can use async-await with Promises only and Node's core https module does not have build in promise support. So you first have to convert it into the promise format and then you can use async-await with it.

https://www.npmjs.com/package/request-promise

This module has converted the core http module into promisified version. You can use this.

Upvotes: 0

Related Questions