我想知道您对ES6 Promise (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise)的这种扩展有什么看法:
Promise.create = function() {
var deferred;
var promise = new Promise(function (resolve, reject) {
deferred = {
resolve: resolve,
reject: reject
};
});
promise.deferred = deferred;
return promise;
}这样就避免了使用第一个回调来获得更干净的代码:
var requestsdeferred = Promise.create();
obj.myFunctionWithCallback(function(){
obj.mySecondFunctionWithCallback(function(){
requestsdeferred.resolve('all done!');
});
});
requestsdeferred.then(function(result) {
});而不是:
var p = new Promise(function(resolve, reject){
obj.myFunctionWithCallback(function(){
obj.mySecondFunctionWithCallback(function(){
resolve('all done!');
});
});
});
p.then(function(){
});需要回调。
你觉得呢?
发布于 2015-09-24 09:32:29
promise的正确/常规用法也不是。通常使用promise的方法是:
ajax.get('/get').then(function(){
return ajax.get('/cart');
}).then(function(){
alert('all done!');
});Promises链,您可以从then处理程序返回一个promise,它将导致从then返回的promise等待其完成并采用其状态。
当然,除非承诺依赖,否则您可以(很可能应该)并发地执行它们:
Promise.all([ajax.get("/get"), ajax.get("/cart")]).then(function(results){
// both done here, concurrently
});避免explicit construction anti-pattern,不需要创建一个延迟的。之所以API看起来不像你所描述的那样,是因为如果你同步throw,它将被转换成一个拒绝,并且你不需要在你的代码中同时添加一个.catch和一个catch (e){处理程序,这很容易出错。
https://stackoverflow.com/questions/32751901
复制相似问题