Promises和Express 4.x - TypeError:无法读取属性"然后"未定义的

时间:2017-09-09 20:59:17

标签: javascript node.js express asynchronous requestjs

[编辑]在尝试实施承诺时,我收到以下错误:
TypeError:无法读取属性"然后"未定义的

的getResult(选项1)的。然后(函数(体){...

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 个答案:

答案 0 :(得分: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);
})