[API Break] .join() and .synchronize() now pass back multiple arguments per promisable

1 view
Skip to first unread message

AJ ONeal

unread,
Aug 21, 2010, 5:27:13 PM8/21/10
to futures-j...@googlegroups.com
Up until now, the documentation has only documented this functionality:

var p = Futures.promise()
p.when(function(result) { /* do stuff */ } );
// some time later
p.fulfill(data);



All along you've actually been able to do this (or else I wouldn't have been able to implement `.join()`):

var p = Futures.promise()
p.when(function(result1, result2) { /* do stuff */ } );
// some time later
p.fulfill(data1, data2);



But .join() and .synchronize() have worked like this:

Futures.join(promise1, promise2, ..., optional_params).when(function (result1, result2) {
  // result1 is arguments[0] of promise1
  // result2 is arguments[0] of promise2
});



Now .join() and .synchronize() give you the full arguments array:

Futures.join(promise1, promise2, ..., optional_params).when(function (result1, result2) {
  // result1[0] is Array.prototype.slice.call(arguments)[0]
  // the fix is to add [0] to your named arguments
})



If you're using the array you can call .map() (ECMAScript 5 or using underscore.js):

Futures.synchronize([promise1, promise2, ...], optional_params).when(function (results_array) {
  results_array = results_array.map(function(args) {return args[0]});
  // the rest of your code as per usual
})



The benefit to this approach is that it works better with libraries that expect to be able to pass multiple parameters.
Consider this example for Node.js

var sys = require('sys'), 
  exec = require('child_process').exec, 
  child,
  Futures = require('futures');
  file_list = [file1, file2, file3],
  promises = [];

file_list.forEach(function(filename) {
  var p = Futures.promise()
  child = exec('cat ' + filename + ' | wc -l', p.fulfill);
  promises.push(p);
});

Futures.join(promises).when(function(results) {
  results.forEach(function(args) {
    var error, stdout, sterr;
    error = args[0];
    stdout = args[0];
    stderr = args[1];
    // do stuff
  });
});


I'm open to any questions, comments, discussion.

AJ ONeal
Reply all
Reply to author
Forward
0 new messages