
如题。因为业务需求,有个地方需要进行 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 Feb 7, 2017 不关 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 Feb 7, 2017 via iPhone 使用 promise.all 另外官方已经推荐 axios |
3 zhuangtongfa Feb 7, 2017 promise.all |
4 zhuangtongfa Feb 7, 2017 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 Feb 7, 2017 如果你是第二步依赖第一步的结果,第三步依赖第二步的结果。那写出来肯定是一个套另一个的。 Promise 不是拿来解决这种问题的。 |
7 matts8023 OP @zhuangtongfa 谢谢,的确优雅了很多! |
8 matts8023 OP @ChefIsAwesome promise.all 可以做到这种控制执行先后顺序的效果 |
@matts8023 all 是几个东西同时出去,等全部完成后收集结果。没有依赖关系。 |
10 zhuangtongfa Feb 7, 2017 |
11 zhuangtongfa Feb 7, 2017 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) } |