Promises and Express 4.x - TypeError: Cannot read property "then" of undefined

441 views Asked by At

[EDIT] While trying to implement the promise I get the following error:
TypeError: Cannot read property "then" of undefined

getResult(options1).then(function(body){...

let options1 = {...};

app.post("/webhook", function (req, res) {
  if (req.body.object_type === "activity" && req.body.aspect_type === "create"){
    getResult(options1).then(function(body){
      res.sendStatus(body.main.temp_max);
    })
  }
});


// listen for requests :)
var listener = app.listen(process.env.PORT, function () {
  console.log('Your app is listening on port ' + listener.address().port);
})


function getRequest(options){
    return new Promise(function(resolve, reject){
        request(options, function (error, response, body) {
            if (error) reject(new Error(error));
            var body = JSON.parse(body);
            resolve(body);
            console.log(body)
        })      
    })
}


function getResult(options){
    getRequest(options).then(function(body){
        // you have the body of the first response
        let options2 = { ...};
        // construct a options2 using this body
        return getRequest(options2);
    })
}
1

There are 1 answers

2
marvel308 On BEST ANSWER

you can do it in the following way

function getRequest(options){
    return new Promise(function(resolve, reject){
        request(options, function (error, response, body) {
            if (error) reject(new Error(error));
            var body = JSON.parse(body);
            resolve(body);
        })      
    })
}


function getResult(options){
    return getRequest(options)
    .then(function(body){
        // you have the body of the first response
        let options2 = {};
        // construct a options2 using this body
        return getRequest(options2);
    })
}

let options1 = {};
// initial options

getResult(options1).then(function(body){
    res.sendStatus(body.main.temp_max);
})