javascript 回调和承诺有什么区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14244775/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 21:07:53  来源:igfitidea点击:

What is the difference between callback and promise

javascript

提问by NSS

Possible Duplicate:
What are the differences between Deferred, Promise and Future in Javascript?

可能的重复:
Javascript 中的 Deferred、Promise 和 Future 之间有什么区别?

Can someone point out what are the differences are between callbacks and promises? When should one use promise etc?

有人可以指出回调和承诺之间有什么区别吗?什么时候应该使用承诺等?

Also links on how to create and use promises will be appreciated.

还将感谢有关如何创建和使用承诺的链接。

回答by Ben McCormick

Promises provide a more succinct and clear way of representing sequential asynchronous operations in javascript. They are effectively a different syntax for achieving the same effect as callbacks. The advantage is increased readability. Something like this

Promise 提供了一种更简洁明了的方式来表示 JavaScript 中的顺序异步操作。它们实际上是一种不同的语法,用于实现与回调相同的效果。优点是增加了可读性。像这样的东西

aAsync()
  .then(bAsync)
  .then(cAsync)
  .done(finish);

is much more readable then the equivalent of passing each of those individual functions as callbacks, like

比将每个单独的函数作为回调传递的等价物更具可读性,例如

Async(function(){
    return bAsync(function(){
        return cAsync(function(){
            finish()
        })
    })
});