0

[编辑] 在尝试实现承诺时出现以下错误:
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);
    })
}
4

1 回答 1

0

您可以通过以下方式进行

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);
})
于 2017-09-09T21:12:47.637 回答