nad
nad

Reputation: 2860

nested promise with request.post

I am creating a POST request and if the request is successful, I am creating a Cisco Spark chatroom (similar to slack). Inside the POST request I am updating part of a variable (array) inside the POST request success and other part of the variable inside the Cisco Spark chatroom creation success.

So I think I need nested promise here so that I have the entire variable available as I need. But I am not sure how to do this.

The original code looks like below:

var request = require('request');
var array = [];
  myObj = new Object()
  request.post({
          url: urlServiceNow,
          headers: headers,
          rejectUnauthorized: false,
          requestCert: false,
          agent: false,
      },function (response, err, body){
          var createJSON = JSON.parse(body);
          array.push(createJSON.result.sys_id);
      }.bind(this));
    ciscospark.rooms.create({title: `AppDNotification`})
      .then((room) => {
        array.push(room.id)
        myObj[valEventTime] = array;
        imdb.push(myObj)
        return Promise.all([
          //more code
        ]).catch((error) => {
          console.log(`Error: \n${error}`);
        })
        .then(() => ciscospark.messages.create({
            markdown: messageToSend,
            roomId: room.id
          }))
          .catch( (error) => {
            console.log(`Error: \n${error}`);
        });
      });

I updated the code with a .then after the .bind like below

request.post({
        url: urlServiceNow,
        headers: headers,
        rejectUnauthorized: false,
        requestCert: false,
        agent: false,
    },function (response, err, body){
        var createJSON = JSON.parse(body);
        array.push(createJSON.result.sys_id);
    }.bind(this))
    .then(() => ciscospark.rooms.create({title: `AppDNotification`}))
    .then((room) => {

       //rest of the code
    })

But I am getting error

TypeError: request.post(...).then is not a function

Please suggest.

Upvotes: 0

Views: 655

Answers (2)

nad
nad

Reputation: 2860

Solved this with request-promise

var rp = require('request-promise');

// Configure the POST request
var optionsPOST = {
    url: urlServiceNow,
    method : 'POST',
    headers : headers,
    rejectUnauthorized: false,
    requestCert: false,
    agent: false
}

rp(optionsPOST)
    .then(function (parsedBody) {
        var post = JSON.parse(parsedBody);
        console.log(post)
        console.log(post.result.sys_id)
        ciscospark.rooms.create({title: `AppDNotification`})
          .then((room) => {

            return Promise.all([
              ciscospark.memberships.create({
                roomId: room.id,
                personEmail: `[email protected]`
              }),
              ciscospark.memberships.create({
                roomId: room.id,
                personEmail: `[email protected]`
              }),
            ]).catch((error) => {

              //Handle Error Here
              console.log(`Error: \n${error}`);

            })
            .then(() => ciscospark.messages.create({
                markdown: "Hi",
                roomId: room.id
              }))
              .catch( (error) => {
                console.log(`Error: \n${error}`);
            });
          });
    })
    .catch(function (err) {
        console.log("fail")
    });

Upvotes: 1

Kirk Larkin
Kirk Larkin

Reputation: 93173

Looking at the documentation for request, promises are not supported:

request supports both streaming and callback interfaces natively. If you'd like request to return a Promise instead, you can use an alternative interface wrapper for request. These wrappers can be useful if you prefer to work with Promises, or if you'd like to use async/await in ES2017.

The documentation continues on to suggest using one of a few different versions that do support promises:

request-promise (uses Bluebird Promises)
request-promise-native (uses native Promises)
request-promise-any (uses any-promise Promises)

Upvotes: 2

Related Questions