Promise

//https://github.com/unscriptable/promises/
 
function Promise() {
    if (!(this instanceof Promise)) {
        return new Promise();
    }
    var status = 'pending';
    var self = this;
    var callbacks = [];
    this.resolve = function(result) {
        complete('fulfilled', result);
    };
    this.reject = function(result) {
        complete('rejected', result);
    };
 
    this.then = function(success, failure) {
        callbacks.push({fulfilled: success, rejected: failure});
        return this;
    };
 
    function complete(type, result) {
        status = type
        self.resolve = self.reject = function() {
            throw new Error("Already completed, promise is now read-only");
        };
        while (callbacks[0]) {
            callbacks.shift()[type](result);
        }
    }
 
}
 
function imageLoader(src) {
    var promise = new Promise();
    var img = document.createElement('img');
    img.onload = function() {
        setTimeout(function() {
            promise.resolve(img)
        }, 2000)
    };
    img.onerror = function() {
        promise.reject(new Error('Image not found: ' + src));
    };
    img.src = src;
    return promise;
}
 
 
 
 
imageLoader('http://google.com/favicon.ico')
        .then(displayImage, printError)
        .then(printFinished);
 
function displayImage(img) {
    document.body.appendChild(img);
}
 
function printError(msg) {
    window.console.error(msg)
}
 
function printFinished(img) {
    window.console.log(img.src + ' loaded');
}
 
/disk_1/www/cz/ladariha/wiki/data/pages/programovani/javascript/promise.txt · Poslední úprava: 2013/07/06 21:40 autor: ladariha
 
Kromě míst, kde je explicitně uvedeno jinak, je obsah této wiki licencován pod následující licencí:CC Attribution-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki