Protractor request and request promise.

Installing Request:

 npm i request 

Using request:

Basic post:

      let body=  {
          url: browser.params.url,
          headers: {
            'X-Octopus-ApiKey': browser.params.apiKey,
          },
          body: JSON.stringify(this.createOctopusTestProjectData)
        };

       function callback(error, response, body) {
                let info = JSON.parse(body);
                console.log(info);
                resolve(info);
            }
        
       request.post(options, callback);

here a call back is invoked and hence its not possible to determine when will the callback be resolved.

sometimes, you will call request in line 1, but the result will be available only by line 5.

This can be avoided by wrapping using a promise function:

promise function:

let requestpromise=async function() {
       const request = require('request');
       let body=  {
          url: browser.params.url,
          headers: {
            'X-Octopus-ApiKey': browser.params.apiKey,
          },
          body: JSON.stringify(this.createOctopusTestProjectData)
        };

          function getIdRequest(options) {
            return new Promise((resolve, reject) => {
            function callback(error, response, body) {
                if (error){
                  reject(error)
                }else if (response.statusCode != 201) {
                  reject(JSON.stringify(response));
                }
                let info = JSON.parse(body);
                console.log(info);
                resolve(info);
            }
              request.post(options, callback);
          });
        }
           return getIdRequest(body);
        }, 


// to get the request body 

response= await  requestpromise()

Using request-promise-native:

The same thing that we did by creating a promise function could be achieved by directly using request-promise-native.

Install request-promise-native:

request-promise-native requires requests, so install both using below command:

npm install --save request
npm install --save request-promise-native

now run:

const request = require('request-promise-native');
let requestpromise=async function() {

        let body={
          url: browser.params.url,
          headers: {
            'X-Octopus-ApiKey': browser.params.apiKey,
          },
          body: JSON.stringify(this.createOctopusTestProjectData)
        };
   
        return request.post(body);
      },

let a= await requestpromise();