Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript asynchronous programming: promises vs generators

Promises and generators allow you to write asynchronous code. I do not understand why both of these mechanisms are introduced in ECMA script 6. When is it best to use the promises, and when the generators?

like image 662
sribin Avatar asked Jan 19 '15 18:01

sribin


People also ask

Are JavaScript promises asynchronous?

A promise is used to handle the asynchronous result of an operation. JavaScript is designed to not wait for an asynchronous block of code to completely execute before other synchronous parts of the code can run. With Promises, we can defer the execution of a code block until an async request is completed.

What is the difference between JavaScript promises and async await?

1. Promise is an object representing intermediate state of operation which is guaranteed to complete its execution at some point in future. Async/Await is a syntactic sugar for promises, a wrapper making the code execute more synchronously.

Is async await built on generators?

Async/await makes it easier to implement a particular use case of Generators. The return value of the generator is always {value: X, done: Boolean} whereas for async functions, it will always be a promise that will either resolve to the value X or throw an error.

What is promises and asynchronous programming?

Promises are a pattern that helps with one particular kind of asynchronous programming: a function (or method) that returns a single result asynchronously. One popular way of receiving such a result is via a callback (“callbacks as continuations”): asyncFunction ( arg1 , arg2 , result => { console . log ( result ); });


2 Answers

There is no opposition between these two techniques: they coexist together complementing each other nicely.

Promises allows you to get the result of an asynchronous operation which is not available yet.
It solves the Pyramid of Doom problem. So instead of:

function ourImportantFunction(callback) {   //... some code 1   task1(function(val1) {     //... some code 2     task2(val1, function(val2) {       //... some code 3       task3(val2, callback);     });   }); } 

you can write:

function ourImportantFunction() {   return Promise.resolve()     .then(function() {         //... some code 1         return task1(val3)     })     .then(function(val2) {         //... some code 2         return task2(val2)     })     .then(function(val2) {         //... some code 3         return task3(val2);     }); }  ourImportantFunction().then(callback); 

But even with promises you must write code in asynchronous fashion - you must always pass callbacks to the functions.
Writing asynchronous code is much harder than synchronous. Even with promises, when the code is huge, it becomes difficult to see the algorithm (it's very subjective, but for the majority of programmers I think it's true).

So we want to write asynchronous code in synchronous fashion. That's where generators are coming to help us.
Instead of the code above you can write:

var ourImportantFunction = spawn(function*() {     //... some code 1     var val1 = yield task1();     //... some code 2     var val2 = yield task2(val1);     //... some code 3     var val3 = yield task3(val2);      return val3; });  ourImportantFunction().then(callback); 

where the simplest possible spawn realization can be something like:

function spawn(generator) {   return function() {         var iter = generator.apply(this, arguments);      return Promise.resolve().then(function onValue(lastValue){       var result = iter.next(lastValue);         var done  = result.done;       var value = result.value;        if (done) return value; // generator done, resolve promise       return Promise.resolve(value).then(onValue, iter.throw.bind(iter)); // repeat     });   }; } 

As you can see value (result of some asynchronous function task{N}) must be a promise. You can't do this with callbacks.

What remains to do is to implement the spawn technique into the language itself. So we are replacing spawn with async and yield with await and are coming to ES7 async/await:

var ourImportantFunction = async function() {     //... some code 1     var val1 = await task1();     //... some code 2     var val2 = await task2(val1);     //... some code 3     var val3 = await task3(val2);      return val3; } 

I recommend you to watch this video to understand more this and some other coming techniques.
Hint: If the guy speaks too fast for you, slow down the speed of playing ("settings" in right bottom corner, or just push [shift + <])

What is the best: only callbacks, or promises, or promises with generators - this is a very subjective question.
Callbacks is the fastest solution possible at this time (performance of native promises are very bad now). Promises with generators give you opportunity to write asynchronous code in synchronous fashion. But for now they are much slower than simple callbacks.

like image 138
alexpods Avatar answered Oct 07 '22 17:10

alexpods


Promises and Generators are different software patterns (constructs):

  1. http://en.wikipedia.org/wiki/Futures_and_promises
  2. http://en.wikipedia.org/wiki/Generator_(computer_programming)

In fact, generators aren't asynchronous.

Generators are useful when you need to get a series of values not at once, but one per demand. Generator will return next value immediately (synchronously) on every call until it reaches the end of the sequence (or endless in case of infinite series).

Promises are useful when you need to "defer" the value, that may not be computed (or may not be available) yet. When the value is available - it's the whole value (not part of it) even it is an array or other complex value.

You can see more details and examples in wikipedia articles.

like image 35
Ivan Samygin Avatar answered Oct 07 '22 18:10

Ivan Samygin