Javascript AJAX中承诺和成功的区别
我有点困惑于Ajax中的成功回访和承诺 让我试着用一个例子来解释我的困惑Javascript AJAX中承诺和成功的区别,javascript,jquery,angularjs,ajax,Javascript,Jquery,Angularjs,Ajax,我有点困惑于Ajax中的成功回访和承诺 让我试着用一个例子来解释我的困惑 $http.get("https://someapi.com").success(function (){}) 在上面的代码中,success是我们的回调函数,它将在异步操作完成时执行。。对吧? 现在来承诺 我们承诺处理成功和失败(解决和拒绝) 现在我的问题是,当我们在Ajax中有回调规定时,为什么我们需要承诺?允许使用回调的结果和/或将几个调用链接在一起来操作结果。通过引入async/await,可以使异步代码更简单
$http.get("https://someapi.com").success(function (){})
在上面的代码中,success是我们的回调函数,它将在异步操作完成时执行。。对吧?
现在来承诺
我们承诺处理成功和失败(解决和拒绝)
现在我的问题是,当我们在Ajax中有回调规定时,为什么我们需要承诺?允许使用回调的结果和/或将几个调用链接在一起来操作结果。通过引入async/await,可以使异步代码更简单
通过回调,这是可以做到的,但是有很多嵌套和潜在的混乱
使用回调:
$http.get('https://something.com/rest/returns5').success(function(result) {
if (result) {
var finalValue = result - 4;
// to use the result you'll need another nested callback here
callback(finalValue); // what scope did this come from? where did this come from? :-)
}
});
承诺:
$http.get('https://something.com/rest/returns5')
.then(function(result) {
return result - 4;
})
.then(function(result) {
// use the result from the previous chained promise call (result - 4)
});
使用承诺的好处在于,它们为异步任务提供了强大的通用接口 公共接口(任何公共接口)的主要好处是,您可以编写和使用基于承诺的高级函数。举个例子,许多promise库提供了一个函数,通常称为
all
,它接受一组promise,并返回一个封装所有promise的新promise。然后你可以写一些东西,比如:
promise.all(promise1, promise2).then(function (value1, value2) {
// blah blah
});
而不是这个金字塔密码
promise1.then(function (value1) {
promise2.then(function (value2) {
// blah blah
});
});
当然,如果您使用的是带有一些已知公共接口的异步任务,则只能使用类似于all
的函数。如果有些人有,那么方法,有些人有。成功方法,等等,这是不可能的
promise
接口还有其他有用的属性,例如。然后promise上的方法返回一个promise-如果您传递的回调返回一个promise,。然后方法返回一个实际等待回调返回的承诺的承诺。换言之:
// p1 is a promise that resolves to 1, when somePromise resolves
var p1 = somePromise.then(function (value) {
return 1;
});
// p2 is a promise that resolves to what someOtherPromise resolves to,
// not to someOtherPromise itself
var p2 = somePromise.then(function (value) {
return someOtherPromise;
});
这使得一个接一个地进行一系列HTTP调用变得非常方便
使用承诺也有一些缺点。。。按照惯例,它们将回调封装在try/catch块中,因此如果抛出异常,它将被捕获,有时是不可见的
somePromise.then(function (value) {
throw 'error';
}).catch(function (error) {
// without this catch block, the error may be eaten invisibly
console.error(error);
});
总之,promise只是一个广泛用于管理异步任务的接口。想用就用,不想用就不要用。看看怎么样?可能是重复的