为什么我们在JS中需要Promise [英] Why do we need Promise in JS
问题描述
我刚刚在 MDN上都读到了关于Promise的内容一个>.我可以理解语法,但是不确定为什么我们需要它.
I've just read about Promise on both MDN. I can understand the syntax but not sure about why we need it.
是否有只能通过Promise来完成的特定情况?还是只是编写更简洁的代码的一种方法?
Is there a specific case that can only be done by using Promise? Or is it just a way to write cleaner code?
推荐答案
承诺使我们能够编写更简洁的代码,但可以减少(或完全删除)回调地狱.
Promises give us the ability to write cleaner code but reducing (or entirely removing) call-back hell.
此外,回调是ES2017中一些新语法功能的中坚力量,例如 async functions
(异步函数),它允许更简洁的代码编写方式.
In addition, callbacks are the backbone of some new syntax features coming in ES2017, such as async functions
, which allows an even cleaner way of writing code.
当您第一次学习语法时,承诺要做的第三件事并不是立即显而易见的-自动错误处理.承诺允许错误沿着链条传递并在一个公共位置进行处理,而不必进行手动错误处理.
The third thing that promises do is not immediately apparent when you first learn the syntax -- automatic error handling. Promises allow errors to be passed down the chain and handled in one common place without having to put in layers of manual error handling.
这篇关于为什么我们在JS中需要Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!