简体   繁体   中英

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

Say there is a HTTP GET callback defined as:

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. 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?

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:

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. Can someone please point me in the right direction?

Your API can easily be modified to return a promise:

 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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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