Moving promises to Q

In Scala, I can take a list of values, display a function of future return through them, and return a future that will collect the values โ€‹โ€‹of these futures into a list (or crash with the first error). More specific:

import scala.concurrent._ import scala.concurrent.ExecutionContext.Implicits.global def doSomething(i: Int): Future[Int] = future(i + 1) // Not really doing much. val incremented = Future.traverse(List(1, 2, 3))(doSomething) 

In this case, the result will be only an enlarged list:

 scala> incremented.onSuccess { case xs => println(xs) } List(2, 3, 4) 

I could also create a list of futures and then turn them into a future containing the same result:

 val incremented = Future.sequence(List(1, 2, 3).map(doSomething)) 

This will give me the same thing, but it creates an extra intermediate collection and is a bit noisier.

I want to do something like this with promises in Q , and it looks like Q.all larger or smaller sequence :

 function doSomething(i) { return Q.fcall(function () { return i + 1; }); } Q.all([1, 2, 3].map(doSomething)).then(function (xs) { console.log(xs) }) 

Is there a way to write a more traverse like version? This is such a basic operation that it seems like there should be a way to do this, but this is my first day with Q, and I'm still working on all overloads of fcall and friends.

+4
source share
2 answers

The answer is directly to your question, but AngularJS uses an extremely shortened version of Q ( $ q ), so you definitely need to do this behavior yourself.

Here is one approach:

 var traverse = function(fn /*values*/) { var values = _.rest(arguments); var promises = _.map(values, fn); return $q.all(promises); }; 

Full example: http://plnkr.co/edit/PGp7QbQYMjOknJwSEn8E

Or with separate parameter lists, as in Scala:

  var traverse = function(/*values*/) { var values = arguments; return function(fn) { var promises = _.map(values, fn); return $q.all(promises); } }; 

Full example: http://plnkr.co/edit/pWoGGaZobbx61tAmUWr9?p=preview

+1
source

You can use the Promise Chaining + Static values โ€‹โ€‹(instead of promises) for the methods and do something like:

 Q.all([1,2,3]) .then(function(xs) { return _(xs).map(doSomething) }) .then(function(xs) { console.log(xs); }); 

If you need a traverse function like this, you can easily implement it yourself

Hope this helps!

0
source

Source: https://habr.com/ru/post/1494829/


All Articles