回调或承诺? [英] Callback or Promise?

查看:162
本文介绍了回调或承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用javascript异步错误捕获机制时,我最后问自己,使用promise而不是回调有什么区别,除了事实promise可能更多的糖语法。



例如,让我们考虑

  function setPromise(){
var message =awesome ;
var deferred = new $ .Deferred();
setTimeout(function(){deferred.resolve(message)},3000);
return deferred.promise();
}

var promise = setPromise();

promise.done(function(message){
console.log(promise done with message:+ message);
});

  function setCallback(doneCallback){
var message =awesome;
setTimeout(function(){doneCallback(message)},3000);
}

setCallback(callback)

function callback(message){
console.log(callback done with message:+ message);
}

两者都作为关闭,都允许发送参数等。 / p>

那么有什么区别?

解决方案

Promises建立在回调之上。后者更原始,更一般,当你需要做复杂的事情,需要更多的工作。



对于你的例子,他们做了几乎相同的事情。但是,假设您想要同时解决三个问题(假设AJAX同时请求三个资源),并在所有三个都完成后继续。它与承诺无关,因为基本上没有什么变化;但是有回调,你需要设置一些标志/计数器,并自己识别成功和失败状态 - 更多的工作。


While playing with javascript asynchronous error-catch mechanisms, I ended up asking myself what is the difference between using a promise instead of a callback, beside the fact promises are maybe more sugar syntactic.

For example, lets consider

        function setPromise() {
            var message = "awesome";
            var deferred = new $.Deferred();
            setTimeout(function(){deferred.resolve(message)},3000);
            return deferred.promise();
        }

        var promise = setPromise();

        promise.done(function (message) {
            console.log("promise done with message : " + message);
        });

and

        function setCallback(doneCallback) {
            var message = "awesome";
            setTimeout(function(){doneCallback(message)},3000);
        }

        setCallback(callback)

        function callback(message) {
            console.log("callback done with message : " + message);
        }

Both act as closure, both allow parameters to be sent back, etc.

So what are the differences?

解决方案

Promises are built on top of callbacks. The latter are more primitive, more general, and take more work when you need to do something complex.

For your example, they do pretty much the same thing. However, let's say you want to have three things resolve simultaneously (imagine requesting three resources by AJAX at the same time), and continuing when all three are done. It is trivial to do with promises, since essentially nothing changes; but with callbacks, you need to set up some flags/counters, and recognise the success and fail states yourself - much more work.

这篇关于回调或承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆