RSS
 

Archive for the ‘Programming’ Category

Promises, Promises… Timeout!

25 Apr

I was playing with ES6’s new Promises, for the first time, this week. Then, I was looking at the ugliness of using a browser’s setTimeout() function and thought that it would look better as a Promise.

tl;dr summary: A Simple Promise Version of “setTimeout()”

If we do it right, you simply specify the timeout period and implement a handler for then() to invoke:

timeout(5000) // Delay for 5000 ms
   .then(function () {
      // Do, here, whatever should happen when the time has elapsed…
   });

Or, since this is ES6, we might as well use arrow-function shorthand:

timeout(5000).then( () => {
   // do your thing, here…
})

Implementation

The setTimeout() already functions a bit like a Promise, without matching the promise-pattern and syntax, so converting it to a Promise is pretty easy:

function timeout(delay) {
   return new Promise( 
      (resolve, reject) => setTimeout( resolve, delay )
   )
} // timeout()

This all, in contrast to the “old” way of using setTimeout():

setTimeout(function () {
   // This is where I do my thing, when the timer pops…
}, 5000);

It just looks ugly; the invocation of the timer and its delay-time property is mingled with what happens when the timer triggers. With the promise pattern, the semantics of the invocation and the handling are discretely organized between the timeout() and its then() handler.

Missing Promises

There are a few things missing.

  1. Cannot cancel a timer.
  2. Even if the timer were cancelable, there ought to be a way to handle it, just as a Promise allows.

We want a cancel() (or perhaps reject()) method. And, if the timer is canceled the promise would be rejected; maybe like so:

let timer = timeout(5000)
.then(id => console.log(id+' completed'))
.catch(err => console.log(err, ' caught!!!'))
// timer.cancel() // Can be canceled

So, how about this… the timeout() function remains dead-simple:

function timeout(delay) 
{
	let promise
	let timeout_reject;		// Save reject() for use during cancel()
	let timeout_timerid;	// Save setTimeout() id for use during cancel()
	function resolver(resolve, reject) // Resolver implements timeout
	{
		timeout_reject = reject
		timeout_timerid = setTimeout(() => resolve(timeout_timerid), delay)
		console.log('resolver:', delay, timeout_timerid )
	}
	promise = new Promise(resolver)	
	promise.cancel = () => {
		clearTimeout(timeout_timerid); 
		timeout_reject(`Timer ${timeout_timerid} canceled`) 
	}
	return promise			// Return promise for "use" by caller
}

cancel() method is attached to the Promise instance, returned. If it is ever invoked, the timer is canceled and promise’s reject() is invoked.

It feels like this is desiring a class to encapsulate the settings attached to the Promise. It bloats the code, and there isn’t much of a win, so this is just for consideration.

function timeout(delay) {
	class Internal {
		attach(promise) {
			promise.cancel= this.cancel.bind(this)
			promise.timer = this
		}
		resolver(resolve, reject) {
			this.reject = reject
			this.timerid = setTimeout(resolve, delay)
			console.log('resolver:', delay,this.timerid) 
		}
		cancel() {
			clearTimeout(this.timerid); 
			this.reject(`timer ${this.timerid} canceled`)
		}
	}

	let tracker=new Internal()
	let promise = new Promise(tracker.resolver.bind(tracker))
	tracker.attach(promise)
	return promise
}

If I were more expert, I might know how to integrate the “internal” class so it appears to derive from Promise. Part of the challenge is that the a resolver function must be passed to the Promise constructor; this prevents useful things from being done before the Promise constructor but before the resolver is invoked.

The slowness of talking across the Internet to grab the various blobs of information and services has pushed web-based applications away from sequential, serial processing towards programs that handle tasks simultaneously—or, at least, do not block the user from seeing and interacting with the application. Part of the evolution is to make it easier for programmers to write such code. I was gonna write an intro to Promises, here, but it’s already been covered by a lot of others, very well. Take a look at the YouTube videos, below.

I’m open to suggestions about how to make this a universal replacement for setTimeout(). Let me know what you think.

Resources

 
 

Simplicity via PHP Frameworks

05 Apr

PHP language and web-technologyA long time ago, I’d endeavored to create my own lightweight PHP framework, ccPHP. It was a good exercise, but never reached prime time. Around that time I began to notice others endeavoring to do the same thing (i.e., create simpler, lighter weight PHP frameworks that didn’t take more time to learn than to implement the project). I’ve been away for a while and things have changed.

  1. The continued refinement and simplification of frameworks.
  2. The greater emphasis on frontend apps to do more of the work that used to be done in the middle tier.
  3. The ubiquity of RESTful interfaces, the dividing line between front-ends and servers.

Micro-PHP Frameworks

I doubt that I will ever finish my own framework, now that others are a lot closer to the goals that I was moving towards. And, right now, I simply want to find a lightweight modular frameworks that truly help me get my core work done. Dragan Gaic did a great survey of the PHP hot frameworks in Top 12 Best PHP RESTful Micro Frameworks (Pro/Con).

A key feature of such frameworks is for them to be modular to allow me to pick and choose only the components I need, rather than have to install, understand, and run a bunch of functionality that I do not need. It makes it harder for the developer and impacts performance of the results. Model-View-Controler (MVC) is a common software architecture pattern. With the client side being far more capable of managing the view part, on its own, the server side can be simpler. Instead of cluttering up the server-side app with trying to display information, it can simply focus on securing data and access and providing data services via RESTful interfaces.

So, what I am looking for are pieces to help me access persistent data and build RESTful interfaces. And something to help keep all the code flow organized. Based on the article, I can look at Silex, Slim, Lumen, or Phalcon for the latter. For database access, Ive worked with RedBeans before and liked it, so I will probably pick that up again. If one of the frameworks doesnt help implement and configure a RESTful interface simply, then I may get back into the framework building business again.

Model: RedBeans
View: Frontend client
Controler: one of SilexSlimLumen, or Phalcon

A WordPress bug allowed my website to be hacked. I thought this was lost forever until I thought to reconstitute it from http://Archive.org!!

 

Activating OS X’s Builtin Apache Web Server and PHP

14 Jan

As I mentioned in my prior post OS X Command-line Dev Tools—Install Shortcut, OS X comes with a variety of built-in tools suited for developers. Unfortunately, Apple has seen fit to hide one of the most important of them: the web server. Despite that, they are easily unlocked if you know how. This applies to Mountain Lion (10.8) and (though I haven’t tried it, yet) Mavericks (10.9). Though you can install separate installations, I don’t like to install anything extra, unless I must. Read the rest of this entry »

 

Command line clipboard in OSX and Cygwin

03 Dec

I use the command line a lot, even though I am on a graphical user-interface like Windows or OSX. And since I’m lazy, I write a lot of scripts to perform repetitive tasks. The downside of command-line is that there is no standard way to interact with GUI features. I stumbled across a command in OSX, recently that allows command line programs to copy/paste between the clipboard that we’re so used to using.

OSX pbpaste and pbcopy

OSX has two commands, pbpaste and pbcopy, Read the rest of this entry »

 

PHP Recipe to Show Source-code

19 Nov

PHP programming referenceHere is a simple Web 1.5 (static HTML with a little bit of styling and JavaScript) recipe to allow a viewer of your web page to see the PHP source code of the page with a minimal amount of JavaScript and a little CSS manipulation—good for showing the work you’ve done to others. Or for embedding in your own source, in debug mode, so that teammates can see each others’ work.

See the example code at: http://cachecrew.com/sample_code/highlight_file.php and http://cachecrew.com//sample_code/highlight_file2.php.

The PHP and HTML Read the rest of this entry »

 

OS X Command-line Dev Tools—Install Shortcut

12 Nov

Xcode command-line toolsAmong those around me, in world of tech startups (even in the vicinity of the world of Windows), MacBooks are used almost universally. I can’t explain the discrepancy between what I see around me and the data you usually read; but I do know that as a technical platform, OS X provides an easier path to development tools. These days, the world driven by web-based applications. A majority of those applications run on Linux-based machines. OS X shares with Linux, a common ancestor, Unix. So, a robust array of common commands come with OS X—ssh, ftp, bash, vi, emacs, etc. But more importantly, OS X comes pre-installed with hottest development tools used for web development, today—Ruby, Python, PHP, Apache, memcache, etc. This means a developer can write web applications without even being connected to the Internet!

There are more tools available with the free download of Xcode, Read the rest of this entry »

 

Self-documenting Bash Scripts Using Heredoc

22 Jul

It is surprising how quickly we forget how to use scripts we had written, let alone, what they were for. So it is even more difficult for others to know how and whether to use your script. You can avoid wasting the efforts you put into the problems you solved with your script by simply adding some friendly “help” output.

Here is some basic information you should include:

  • Summary description
  • Form of use—basic syntactic usage
  • Description of usage syntax; i.e., input parameters
  • More detailed information, if necessary. Read the rest of this entry »
 

Server Handling of Accept HTTP Headers

31 Aug

When a browser (or any web client) requests content from a web server, it can tell the server what types of content type it can interpret (HTML, text, audio, etc.). The underlying HTTP protocol allows these to be specified via “header” settings—metadata that is sent before any actual content, describing characteristics about the content. The browser can send an “Accept” header—to describe what it accepts—and the server responds with a “Content-type” header. The Accept header can be quite elaborate, but what happens when what happens when these conflict? Read the rest of this entry »

 

The ccPhp Framework: Installation

24 May

I have a whole series of posts, waiting in draft, describing my evolving PHP framework, I call ccPhp. If you have nothing better to do than play with someone else’s dalliances, then here is a quick installation guide.  A little backwards, because I’ve yet to publish reasons why you’d want to. But, if, after my eventual publications describe this framework, you decide to install it, this is the quickest place to see how to do that.

The following describes only one way to arrange the setup.  I have designed the framework with few cross-dependencies.  After my “standard” setup description, I will describe the few file dependencies so that you easily define your own file organization. (If you are on Windows, you can extrapolate the appropriate things to do there). Read the rest of this entry »

 

Avoid Objective-C Bugs w/Properties and Instance Variables (ivar)

25 Nov

Objective-C is the programming language of choice for iOS an Mac OSX programming, so becoming proficient in native programming for those platforms is essential to building great applications. Apple emphasizes that programmers must understand the “retain-release” model of how to manage objects. True, but this is not enough. Unfortunately, Objective-C makes it exceedingly easy to inadvertently write code that breaks the retain-release model, leading bugs that cause programs to crash.  You can adopt some practices to avoid such problems. Read the rest of this entry »