我用 Nodejs 写了一个 API 接口,用于请求指定数据。这个接口会请求三个其他的 API:
我的目的是同时(并发)请求上面这三个 API,然后汇总请求到的结果,返回给客户端。
请问这个可以实现吗,对 Nodejs 不懂?
1
hgjian 2020 年 8 月 20 日 via Android
promise.all ?好像可以
|
2
flowfire 2020 年 8 月 20 日 await Promise.all([
fetch("url1"), fetch("url2"), fetch("url3"), ]) |
3
c6h6benzene 2020 年 8 月 20 日 via iPhone
如果用包装好的包如 axios,可以用 axios.all([request1, request2, request3,...).then(axios.spread(response1, response2, response3) => {})。
|
4
coderxy 2020 年 8 月 20 日
promise.all
|
5
4196 2020 年 8 月 20 日
不是 Nodejs 不懂的问题,你应该多去学下 js,特别是 es6+的😄
|
6
dfourc 2020 年 8 月 20 日
1.回调嵌套
2.请求成功计数 3.promise.all |
7
buffzty 2020 年 8 月 20 日
async ()=>{
const task1 = fetch1() const task2 = fetch2() const task3 = fetch3() // try catch const task1Resp = await task1 const task2Resp = await task2 const task3Resp = await task3 // logic } |
8
azcvcza 2020 年 8 月 20 日 promise.all 建议里边包一层 promise,这样即使请求错误 promise.all 也不会挂掉往下走了
|
11
JaydenC 2020 年 9 月 21 日
用这个就好了,总有你想要的流程控制方式
https://caolan.github.io/async/v3/docs.html#parallel async.parallel([ function(callback) { setTimeout(function() { callback(null, 'one'); }, 200); }, function(callback) { setTimeout(function() { callback(null, 'two'); }, 100); } ], // optional callback function(err, results) { // the results array will equal ['one','two'] even though // the second function had a shorter timeout. }); // an example using an object instead of an array async.parallel({ one: function(callback) { setTimeout(function() { callback(null, 1); }, 200); }, two: function(callback) { setTimeout(function() { callback(null, 2); }, 100); } }, function(err, results) { // results is now equals to: {one: 1, two: 2} 这里执行所有请求返回后的回调 }); |