Skip to content

Instantly share code, notes, and snippets.

@rsbondi
Created April 26, 2015 15:46
Show Gist options
  • Save rsbondi/829aa61beadc6366c701 to your computer and use it in GitHub Desktop.
Save rsbondi/829aa61beadc6366c701 to your computer and use it in GitHub Desktop.
Not pretty, not chainable, but more error tolerant promise using knockout observable
;(function(ko) {
ko.promise = function() {
var self = this
var promise = ko.observableArray([])
promise.get = function(url) {
var request = new XMLHttpRequest();
request.promise = ko.observable({})
request.open('GET', url, true)
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
request.promise({success: true, text: request.responseText})
} else {
request.promise({success: false, text: "server returned error"})
}
};
request.onerror = function() {
request.promise({success: false, text: "connection error"})
};
request.send()
return request.promise
}
promise.all = function() {
self.completed = []
var narg = arguments.length
for (var i = 0; i < narg; i++){
arguments[i].subscribe(function(a) {
self.completed.push(a)
if(self.completed.length == narg) {
promise(self.completed)
}
})
}
}
return promise
}
})(ko)
@rsbondi
Copy link
Author

rsbondi commented Apr 26, 2015

Not pretty, not chainable, but more error tolerant promise using knockout observable
use:

// multi
var p = new ko.promise()
p.all(p.get('a.json'), p.get('b.json'))
p.subscribe(function(data) {
  data.map(function(v) {
    console.log('all returned', v)
  })
})

// single
var c = p.get('c.json')
c.subscribe(function(data) {
  console.log('single get', data)
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment