### promise 是如何解決回調嵌套的。
比如我們需要發送ajax請求,需要對請求回來的數據再一次操作,再次發送請求,照以前的情況我們應該這樣寫:
~~~
$http({
method: 'GET',
url: '/carrots-admin-ajax/a/article/6211',
}).then(function (response) {
if (response.data.code === 0) {
//從接口獲取數據,然后ng-repeat出來
$scope.articleList = response.data.data.articleList;
//第二次回調
$http({
method: "PUT",
url: '/carrots-admin-ajax/a/u/article/status',
params: {id: 6211, status: 1},
headers: {'Content-type': 'application/json'}
}).then(function (res) {
if (res.data.code === 0) {
//dosomething
}
})
} else {
alert('錯誤')
}
})
~~~
使用了promise,每當我們需要回調時,就把回調函數return出去,然后在下一個then執行回調函數的回調函數;
~~~
//一個回調函數
function http2() {
return $http({
method: 'PUT',
url: '/carrots-admin-ajax/a/u/article/status',
params: {id: 6211, status: 1},
headers: {'Content-type': 'application/json'}
})
}
$http({
method: 'GET',
url: '/carrots-admin-ajax/a/article/6211',
}).then(function (response) {
if (response.data.code === 0) {
//從接口獲取數據,然后ng-repeat出來
$scope.articleList = response.data.data.articleList;
return http2()//如果請求成功,執行另一個ajax請求,把該請求return出去。
} else {
alert('錯誤')
}
})
//執行return函數的回調函數
.then(function (res) {
console.log(res);
});
~~~
return 和不return的區別?
- 空白目錄
- Javascript
- angularjs
- 自定義指令
- scope
- 自定義指令的封裝
- 自定義指令限制只能輸入數字
- 輪播圖
- 寫angular的順序
- $state
- video
- Es6
- Let
- 箭頭函數
- export
- promise
- 函數
- vue
- vue安裝,以及項目結構
- vue的使用
- easy-vue
- vue起步
- vue基礎
- vue-router
- vue-各文件的依賴關系
- vuex
- vue使用sass語法
- mpvue使用wx.parse
- vue-cli 構建vue項目
- vant的使用
- vue使用插件及常見問題
- 原生Js
- 數組
- ajax
- 執行上下文
- 正則表達式
- jqurey
- jqurey-mobile
- html5
- 工具
- svn使用總結
- webpack
- webpack的構建
- WebStorm
- 切圖相關
- 蘋果手機注意事項
- other
- 前端的價值
- 面試相關
- css
- 小程序如何引用外部字體
- 流的理解
- 替換元素
- content和偽元素
- padding和background 繪制圖形
- css圓角,陰影,漸變
- line-height verticle-align
- 使用background繪制4個直角
- android的字體偏上的問題
- 小程序
- 小程序常見問題
- 小程序常用效果
- mpvue
- nodejs
- 前端工程化學習筆記
- mork.js學習