本文介绍了Node.js中的同步请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我需要按顺序调用3 http API,那么以下代码会是更好的选择:
If I need to call 3 http API in sequential order, what would be a better alternative to the following code:
http.get({ host: 'www.example', path: '/api_1.php' }, function(res) { res.on('data', function(d) { http.get({ host: 'www.example', path: '/api_2.php' }, function(res) { res.on('data', function(d) { http.get({ host: 'www.example', path: '/api_3.php' }, function(res) { res.on('data', function(d) { }); }); } }); }); } }); }); }推荐答案
使用诸如 Futures 之类的延期
Using deferreds like Futures.
var sequence = Futures.sequence(); sequence .then(function(next) { http.get({}, next); }) .then(function(next, res) { res.on("data", next); }) .then(function(next, d) { http.get({}, next); }) .then(function(next, res) { ... })如果您需要传递范围,则只需执行以下操作
If you need to pass scope along then just do something like this
.then(function(next, d) { http.get({}, function(res) { next(res, d); }); }) .then(function(next, res, d) { }) ... })更多推荐
Node.js中的同步请求
发布评论