I am trying to create a function that returns a promise so it can be chained together and integrated with some other functions.
When I try to run, I get the following error:
TypeError: Cannot read property 'then' of undefined
Can I put the promise inside .end
or does it need to be wrapped around the entire function body? Can errors be properly handled like this?
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)
}
})
});
};
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)
}
})
});
}