标签:
Starting with ECMAScript 6, JavaScript gains support for Promise
objects allowing you to control the flow of deferred and asynchronous operations.
A Promise
is in one of these states:
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.
标签:
原文地址:http://www.cnblogs.com/hephec/p/4601265.html