## 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的區別?