javascript - Node.js 和 Express : wait for asynchronous operation before responding to HTTP request

标签 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 ,但我无法使用 promise 或异步/等待来执行它。有人可以指出我正确的方向吗?

最佳答案

您的 API 可以轻松修改以返回 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/*?*/);
   });
 }

既然你有一个 promise ,你可以等待它:

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

   res.json(data);
});

关于javascript - Node.js 和 Express : wait for asynchronous operation before responding to HTTP request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56119131/

相关文章:

javascript - ko.dependentObservable 这个方法如何巧妙地理解依赖关系?

javascript - 构建巨大的单页应用程序、框架选择等

node.js - NodeJs GUI 前端

node.js - `npm link --save` 不更新对我的 package.json 的依赖

javascript - 如何在 Javascript/Typescript 中使用 import 和 require?

Node.js - 扩展 res.render 的 Expressjs 中间件

javascript - 在 Sequelize model.destroy({ chop : true }) does not reset primary key

node.js - 为什么重音字母在express.js 中不能正确解释?

javascript - 如何修改/重新转换 JSON 数组结构

Javascript 按钮值不更新