Autoplay

    Write applicatives for concurrent actions

    Brian LonsdorfBrian Lonsdorf

    We start with two sequential finds using monads, then rewrite our code to achieve two concurrent finds.

    javascriptJavaScript
    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Transcript

    Transcript

    00:00 In this example, we have a DB. This is a marked database that will do a "find" with some ID, some arbitrary ID, and then, set time out for a small amount of time, and then, return as an object here. It's a project with an ID and a title.

    00:13 We would call a report header with two different projects. That is we want to find -- "db find," some ID, let's say "20." We also want to do "db find," let's say "8." This will find two different projects.

    00:24 If I were to call a chain to get Project 1, and then, find a second project, Project 2, and then, we call that report header with both P1 and P2. This would wait for the first find to finish, pass in our project, and then once that is done, call the second find.

    00:42 This is good because we can depend on P1, if we want, in our second find. In this case, we don't care about P1 and P2 being dependent on each other's sequential finds here. What we could do is use applicatives to kick both off at the same time.

    00:54 What we could do is go ahead, and let's put this in a task of report header. Instead of altering our report header to be curtailed, why don't we go ahead and take P1, area of P2, and then recall report header with P1 and P2, like that.

    01:09 We didn't alter the original function. We've made a little task here that is carried. Then, we'll go ahead and apply that to the first find. We'll apply that to the second find. There we are. That's all we have to do. We've found the first thing and the second thing.

    01:22 Notice, these are both kicked off at the same time. It does not wait for one to resolve before it calls the second one.

    01:27 Now, we can call "fork." Cancel that area. Cancel that log. We have here our answer, which will be a report with Project 20 compared to Project 8.

    Discuss

    Discuss