简体   繁体   English

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

[英]Node.js and Express: wait for asynchronous operation before responding to HTTP request

Say there is a HTTP GET callback defined as: 假设有一个HTTP GET回调定义为:

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

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

    res.json(data);
};

Both get_ functions use the fb package to generate a HTTP request and execute a callback when finished. 这两个get_函数都使用fb包来生成HTTP请求并在完成后执行回调。 How can the above GET callback be modified in order to wait for the responses from Facebook and only then send a response to the client? 如何修改上述GET回调以等待来自Facebook的响应,然后才将响应发送给客户端?

At the time being I solved the problem by executing the get_ functions in series and passing them the res (response) argument, with the last function sending the response: 当时,我通过get_执行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);
    });
}

I have found a similar question , but I'm wrapping my head around it, since I can't find a proper way to apply the solution to my problem. 我发现了一个类似的问题 ,但由于无法找到将解决方案应用于我的问题的正确方法,所以我将自己的想法缠住了。 I have tried using the patterns described in this manual , but I can't get it to execute using promises, or async/await. 我已经尝试使用本手册中介绍的模式,但是无法使用promises或async / await来执行它。 Can someone please point me in the right direction? 有人可以指出正确的方向吗?

Your API can easily be modified to return a promise: 您的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/*?*/);
   });
 }

Now that you have a promise, you can await it: 现在您有了一个承诺,您可以等待它:

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

   res.json(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM