首页 > 其他 > 详细

Promises

时间:2015-06-26 00:23:00      阅读:267      评论:0      收藏:0      [点我收藏+]

 

Starting with ECMAScript 6, JavaScript gains support for Promise objects allowing you to control the flow of deferred and asynchronous operations.

Promise is in one of these states:

  • pending: initial state, not fulfilled or rejected.
  • fulfilled: successful operation
  • rejected: failed operation.
  • settled: the Promise is either fulfilled or rejected, but not pending.

技术分享

Loading an image with XHR

A simple example using Promise and XMLHttpRequest to load an image is available at the MDN GitHub promise-test repository. You can also see it in action. Each step is commented and allows you to follow the Promise and XHR architecture closely. Here is the uncommented version, showing the Promise flow so that you can get an idea:

function imgLoad(url) {
  return new Promise(function(resolve, reject) {
    var request = new XMLHttpRequest();
    request.open(‘GET‘, url);
    request.responseType = ‘blob‘;
    request.onload = function() {
      if (request.status === 200) {
        resolve(request.response);
      } else {
        reject(Error(‘Image didn\‘t load successfully; error code:‘ 
                     + request.statusText));
      }
    };
    request.onerror = function() {
      reject(Error(‘There was a network error.‘));
    };
    request.send();
  });
}
 

  

For more detailed information, see the Promise reference page.

Promises

原文:http://www.cnblogs.com/hephec/p/4601265.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!