What are the advantages of Promises over CPS and the Continuation Functor/Monad?

霸气de小男生 提交于 2019-12-01 06:06:48

The disadvantage of any approach that relies on functional composition is that idiomatic JavaScript code sequences are replaced with lists of named functions. Promises themselves suffer from this.

E.g. I see people do what I call callback lite:

let foo = () => Promise.resolve().then(() => console.log('foo'));
let bar = () => Promise.resolve().then(() => console.log('bar'));

foo().then(bar);

This is one approach, but not the only one, and I personally dislike it, the same way I dislike any attempt at replacing JavaScript with English or action lists.

To me, a benefit of promises is that we can avoid the indirection of traditional callbacks altogether and write code in the order things happen, in a forward direction. Arrow functions help:

Promise.resolve('foo')
  .then(foo => {
    console.log(foo);
    return Promise.resolve('bar');
  })
  .then(bar => {
    console.log(bar);
  });

However, this is arguably still an action list.

So to me, the big advantage of ES6 promises is their compatibility with async/await, which let us write idiomatic JavaScript for asynchronous code much like we would synchronous code, albeit not from top-level scope (requires Chrome or Firefox Beta):

(async () => {
  console.log(await Promise.resolve('foo'));
  console.log(await Promise.resolve('bar'));
})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!