Node.js和Express:在响应HTTP请求之前等待异步操作

时间:2019-05-13 19:59:33

标签: javascript node.js express promise async-await

说有一个HTTP GET回调定义为:

router.get('/latestpost', function(req, res, next) {

    var data = new FbData();
    get_latest_post (data);
    get_post_image (data);

    res.json(data);
};

两个get_函数都使用fb package来生成HTTP请求并在完成后执行回调。如何修改上述GET回调以等待来自Facebook的响应,然后才将响应发送给客户端?

目前,我通过依次执行get_函数并将其传递给res(响应)参数,最后一个函数发送响应来解决该问题:

router.get('/latestpost', function(req, res, next) {
    var data = new FbData();
    get_latest_post (res, data);
};


function get_latest_post (res, data) {

    FB.api(_url, function (res_fb) {

        if(!res_fb || res_fb.error) {
            console.log(!res_fb ? 'error occurred' : res_fb.error);
            return;
        }

        // Do stuff with data

        get_post_image (res, data);
    });
}


function get_post_image (res, data) {

    FB.api(_url, function (res_fb) {

        if(!res_fb || res_fb.error) {
            console.log(!res_fb ? 'error occurred' : res_fb.error);
            return;
        }

        // Do stuff with data

        /* At the end send the post data to the client */
        res.json(data);
    });
}

我已经找到了a similar question,但是由于无法找到将解决方案应用于我的问题的正确方法,所以我将头衔缠住了。我尝试使用in this manual中描述的模式,但是无法使用promises或async / await来执行它。有人可以指出正确的方向吗?

1 个答案:

答案 0 :(得分:1)

您的API可以轻松修改以返回承诺:

 function get_post_image (res, data) {
   return new Promise((resolve, reject) => {
    FB.api(_url, function (res_fb) {
      if(!res_fb || res_fb.error) {
        reject(res_fb && res_fb.error);
      } else resolve(res_fb/*?*/);
   });
 }

现在您有了诺言,就可以等待:

 router.get('/latestpost', async function(req, res, next) {
   const data = new FbData();
   const image = await get_post_image (data);

   res.json(data);
});