Skip to content

Instantly share code, notes, and snippets.

@simonwoo
Last active January 20, 2016 10:18
Show Gist options
  • Select an option

  • Save simonwoo/7f6c2aecde316ac5de4d to your computer and use it in GitHub Desktop.

Select an option

Save simonwoo/7f6c2aecde316ac5de4d to your computer and use it in GitHub Desktop.

一个Promise对象代表一个目前还不可用,但是在未来的某个时间点可以被解析的值。它允许你以一种同步的方式编写异步代码。

Promise有三种状态:

  • pending(没有fulfilled或者rejected)
  • fulfilled
  • rejected

Promise的一种实现方式:

var Promise = function () {
  /* initialize promise */
};

Promise.prototype.then = function (onResolved, onRejected) {
  /* invoke handlers based upon state transition */
};
 
Promise.prototype.resolve = function (value) {
  /* move from unfulfilled to resolved */
};
 
Promise.prototype.reject = function (error) {
  /* move from unfulfilled to rejected */
};

Examples:

// chain
function async(value) {  
    // create a deffered, it represents the result of an asynchronic operation.
    var deferred = $q.defer();
    
    var asyncCalculation = value / 2;
    deferred.resolve(asyncCalculation);
    
    return deferred.promise;
}
// (8 + 1) * 2 - 1
var promise = async(8)  
    .then(function(x) {
        return x+1;
    })
    .then(function(x) {
        return x*2;
    })
    .then(function(x) {
        return x-1;
    });

promise.then(function(x) {  
    console.log(x);
});
// promise chain
function async1(value) {  
    var deferred = $q.defer();
    var asyncCalculation = value * 2;
    deferred.resolve(asyncCalculation);
    return deferred.promise;
}

function async2(value) {  
    var deferred = $q.defer();
    var asyncCalculation = value + 1;
    deferred.resolve(asyncCalculation);
    return deferred.promise;
}

function logValue(value) {  
    console.log(value);
}

async1(10)  
    .then(async2)
    .then(logValue);

当我们想返回一个resolved prommise时我们使用$q.when(data) 当我们想返回一个rejected promise时我们使用$q.reject(reason)

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