Wednesday, May 20, 2009

Using Adobe BridgeTalk synchronously

So let's face it : writing synchronous code is a lot easier than writing asynchronous code. I can write asynchronous code easily enough, but it looks so much more cluttered, and/or takes so many more lines of code. I'm a big believer in simplicity.

So, if you want to whip up a simple script, and it doesn't need to win design awards, then I suggest you check out xbytor's cool little trick for using BridgeTalk synchronously. (Search on that page for "Send a synchronous message".)

Nice one, xbytor.

And in case that forum goes down, here's a copy of the most pertinent bit. (See the original thread for more questions, answers and examples.)

First, some utility code :

// Send a synchronous message. The result is returned.
// If a result doesn't come back in 'timeout' seconds, undefined is returned.
BridgeTalk.prototype.sendSynch = function(timeout) {
var self = this;
self.onResult = function(res) {
this.result = res.body;
this.complete = true;
}
self.complete = false;

self.send();

if (timeout) {
for (var i = 0; i < timeout; i++) {
BridgeTalk.pump(); // process any outstanding messages
if (!self.complete) {
$.sleep(1000);
} else {
break;
}
}
}

var res = self.result;
self.result = self.complete = self.onResult = undefined;
return res;
};
// for typos, provide an alias
BridgeTalk.prototype.sendSync = BridgeTalk.prototype.sendSynch;

And now an example of how to use it :

function test() {
var bridgeApp = "bridge-1.0";

if (!BridgeTalk.isRunning(bridgeApp)) {
BridgeTalk.launch(bridgeApp);
}

var bt = new BridgeTalk();
bt.target = bridgeApp;
bt.body = "new Date().toString()";
var res = bt.sendSynch(10);
alert(res);
};

test();

Once again, mega kudos to xbytor. Some coding purists might gag at the internal polling loop, but remember, we're not talking about production scripts released to thousands of users worldwide - we're talking about helping every developer be more productive by writing their own scripts more easily.

3 comments:

Anonymous said...

Request you to use a white background. Black is difficult to read and also not good for the eyes.
PS: The article is great :-)

man9ar00 said...

Do you have an example for synchronous HTTP requests through Bridgetalk?

Unknown said...

Works like a charm. I made one important modification, because your solution takes at least 1 full second to return, not so handy if you need to send dozens of commands.

for (var i = 0; i < (timeout*200); i++) {
  BridgeTalk.pump(); // process any outstanding messages
  if (!self.complete) {
    $.sleep(5);
  } else { break; }
}

Used no-break spaces to preserve indentation :-)