How to return a promise from a Unirest PUT request

I am trying to create a function that returns a promise so that it can be chained together and integrated with some other functionality.

When I try to run, I get the following error: TypeError: Cannot read property 'then' of undefined

Can I put a promise inside .end

or does it need to be wrapped around the whole body of the function? Can errors be handled correctly?

index.js

const module = require('./module');

var test = {
  name: "Full Name"
};

module.update(test).then((response) => {
  console.log(response);
});

      

module.js

const unirest = require('unirest');

module.exports = {

update: function({name}) {
  unirest.put(someURL)
    .headers({
      'Content-Type': 'application/json'
    })
    .send({
      name: name
    })
    .end(function (response) {
      return new Promise((resolve, reject) => {
        if(response) {
          resolve(response)
        }
        if(error){
          reject(response)
        }
      })
  });
};

      

+3


source to share


1 answer


The root of your function should be the one returning the promise.



update: function(name) {
  return new Promise((resolve, reject) => {
    unirest.put(someURL)
      .headers({
        'Content-Type': 'application/json'
      })
      .send({
        name: name
      })
      .end(function (response) {
        if(response) {
          resolve(response)
        }
        if(error){
          reject(response)
        }
      })
  });
}

      

+5


source







All Articles