Node.js中的同步请求

编程入门 行业动态 更新时间:2024-10-28 22:24:27
本文介绍了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中的同步请求

本文发布于:2023-07-26 14:28:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1216703.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Node   js

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!