Search code examples
asynchronouslanguage-agnosticcoroutine

What's the difference between a coroutine and a promise/future?


From my understanding a coroutine is a function that can pause and continue later. Isn't that the same thing as a promise: a function that stops and continues at some point in the future?

If there is a difference then what do the keywords async and await (or synonymous in other languages) implement, a promise or a coroutine? Or would implementation vary per language?


Solution

  • A Promise completes a Future (What's the difference between a Future and a Promise?)

    A Coroutine is essentially a task that can be paused and resumed. (https://en.cppreference.com/w/cpp/language/coroutines)

    The difference is quite vast. You use a Future to control an asynchronous object, then you use a Promise to complete operations based on the Future. In C++ for example, a Promise is only meant to be fulfilled once whereas a Future will be reset and might be reused.

    A Coroutine may be used to simultaneously work on multiple different operations that cannot complete synchronously, but don't necessarily need to be multi-threaded. (https://support.unity.com/hc/en-us/articles/208707516-Why-should-I-use-Threads-instead-of-Coroutines)

    For example, you may use a Coroutine to handle server connections and simultaneously respond to requests. You will likely use a Promise to await a response back from the server on the client.

    Since you also asked about async and await, from what I am gathering, at least with C# and Node.js it is event driven. Meaning that it is still single-threaded, but when an event occurs it gets handled. (https://learn.microsoft.com/en-us/dotnet/csharp/asynchronous-programming/task-asynchronous-programming-model) However, this will likely vary from language to language.