Js Deferred/Promise/Future compared to functional languages like Scala

前端 未结 4 846
迷失自我
迷失自我 2020-12-05 03:21

I\'m mostly using programming languages like Scala and JavaScript. I\'m trying to understand the similarities and differences in how async reactive programming is used in bo

4条回答
  •  执念已碎
    2020-12-05 03:36

    Yes, and no.

    While extremely similar. With JavaScript Promises that comply to the Promises/A+ spec .then is not really a monadic bind and does .map and .flatMap both. Inside a .then handler when you return a promise it will recursively unwrap it.

    Promise.delay(1000).then(function() {
        return Promise.delay(1000).then(function () {
            return Promise.delay(2000);
        }).then(function () {
            return Promise.delay(5000)
        });
    }).then(function () {
        alert("This is only shown after 8 seconds and not one");
    });
    

    (fiddle)

    You are correct that the standard JS promise libraries and the A+ spec does not feature monadic promises. They have been discussed, and implementations like fantasy-promises exist. They follow a differnet spec and have little adoption. Also see this. There has been ongoing discussion about it in the language design discussion forum - esdiscuss and a monadic .chain method that does not flatmap and allows for monadic promises is considered but unlikely to make it.

    This is for pragmatic reasons. The current way promises are implemented is immensely useful. Rare are the cases you actually want a Future[Future and normally you want continuations to just work in the language. Promises 'borrow' from monads and are 'monadic' in a sense themselves. .then is very close to bind and in my head I use them interchangeably :)

    It is impossible to have a Promise[Promise[Value]] like a Future[Future[Value]] in Scala with most promise libraries. You'd have to wrap it in an object and have Promise[Container[Promise[Value]]].

    Promise.delay(1000).then(function () {
        return Promise.delay(1000).then(function () {
            return {
                wrap: Promise.delay(2000).then(function () {
                    return Promise.delay(5000);
                })
            };
        });
    }).then(function () {
        alert("This logs after 1 second");
        // I've also not seen a really solid use case 
        // except TypeScript type inference which is meh
    });
    

    (fiddle)

    There are also a number of other smaller differences between the two, but generally you are correct in your assertions.

提交回复
热议问题