gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:02:20 25 4
gpt4 key购买 nike

假设有一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com