Node.js同步请求超级请求中的同步请求
如果我需要按顺序调用3个http API,那么对于以下代码来说,这将是一个更好的替代方法:
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
这样的延迟。
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) {
...
})
如果你需要通过范围,那么就做这样的事情
.then(function(next, d) {
http.get({}, function(res) {
next(res, d);
});
})
.then(function(next, res, d) { })
...
})