码迷,mamicode.com
首页 > 其他好文 > 详细

Promises

时间:2015-06-26 00:24:31      阅读:82      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!