我想知道您如何看待这种 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(){
});
需要回调。
你怎么看?
最佳答案
promise 的正确/常规用法也不是。使用 promise 的通常方式是:
ajax.get('/get').then(function(){
return ajax.get('/cart');
}).then(function(){
alert('all done!');
});
Promises 链,您可以从 then
处理程序返回一个 promise,它会导致 then
返回的 promise 等待其完成并呈现其状态。
当然,除非 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){
处理程序到您容易出错的代码。
关于javascript - 扩展 ES6 Promise 以将回调转换为延迟模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751901/