
如题。因为业务需求,有个地方需要进行 3 次 Ajax 请求,不用 Vue-Resource 时写的话就有三层回调,代码得臃肿。后来使用了 Vue-Resource ,以为 Promise 的特性能避免这个问题,没想实际写的时候却陷入同一种思维里。
Vue.$http.get('/test1').then(function() { Vue.$http.get('/test2').then(function() { Vue.$http.get('/test3').then(function(response) { console.log(response); }); }); }); 请问如何优雅的用链式操作写这个 Ajax ?
1 k9982874 2017-02-07 08:56:19 +08:00 不关 vue-resource 的事, promise 基础不扎实。 ```Javascript Vue.$http.get('/test1').then(respOnse=> { // 处理第一次返回的 response return Vue.$http.get('/test2') }).then(respOnse=> { // 处理第二次返回的 response return Vue.$http.get('/test3') }).then(respOnse=> { // 处理第三次返回的 response console.log(response); }).catch(err => { // 处理错误 console.log(err); }) ``` |
2 ccccccc 2017-02-07 09:10:26 +08:00 via iPhone 使用 promise.all 另外官方已经推荐 axios |
3 zhuangtongfa 2017-02-07 09:15:34 +08:00 promise.all |
4 zhuangtongfa 2017-02-07 09:24:21 +08:00 const promises = ["/test1", "/test2", "/test3"] .map(item => { return Vue.$http.get(item) }) // 方法一 Promise.all(promises) .then(res => { console.log(res) }) // 方法二:使用 async/await async function getData() { const res = await Promise.all(promises) } |
5 ChefIsAwesome 2017-02-07 09:33:17 +08:00 如果你是第二步依赖第一步的结果,第三步依赖第二步的结果。那写出来肯定是一个套另一个的。 Promise 不是拿来解决这种问题的。 |
7 matts8023 OP @zhuangtongfa 谢谢,的确优雅了很多! |
8 matts8023 OP @ChefIsAwesome promise.all 可以做到这种控制执行先后顺序的效果 |
9 ChefIsAwesome 2017-02-07 10:52:22 +08:00 @matts8023 all 是几个东西同时出去,等全部完成后收集结果。没有依赖关系。 |
10 zhuangtongfa 2017-02-07 13:35:58 +08:00 |
11 zhuangtongfa 2017-02-07 13:43:12 +08:00 import Promise from 'bluebird' // 方法一 Promise.mapSeries(["/test1", "/test2", "/test3"], url => Vue.$http.get(url)) .then(function (results) { console.log(results) }) // 方法二:使用 async/await async function getData() { const results = await Promise.mapSeries(["/test1", "/test2", "/test3"], url => Vue.$http.get(url)) console.log(results) } |