官术网_书友最值得收藏!

Promises

Promises, in one form or another, have been available in JavaScript for a while. All jQuery users are familiar with the idea. A promise is a reference to a variable that is generated asynchronously and may become available in the future.

The ES5 way of doing things, if you weren't already using some sort of third-party promise library or jQuery's deferred's, was to accept a callback function to an asynchronous method and run the callback upon successful completion, as shown in the following code:

function updateUser(user, settings, onComplete, onError) {
makeAsyncApiRequest(user, settings, function(response) {
if (response.isValid()) {
onComplete(response.getBody());
} else {
onError(response.getError())
}
});
}
updateUser(user, settings, function(body) { ... }, function(error) { ... });

In ES6, you may return a Promise which encapsulates the asynchronous request and either gets resolved or rejected, as shown in the following code:

function updateUser(user, settings) {
return new Promise((resolve, reject) => {
makeAsyncApiRequest(user, settings, function(response) {
if (response.isValid()) {
resolve(response.getBody());
} else {
reject(response.getError())
}
});
});
}
updateUser(user, settings)
.then(
body => { ... },
error => { ... }
);

The real power of promises is that they can be passed around as objects, and promise handlers can be chained.

主站蜘蛛池模板: 时尚| 镇远县| 鹤峰县| 海晏县| 陆河县| 舒兰市| 共和县| 濉溪县| 济宁市| 开鲁县| 云安县| 南皮县| 陆川县| 临潭县| 和林格尔县| 和龙市| 镇雄县| 焉耆| 保定市| 西贡区| 南通市| 韶山市| 南华县| 博兴县| 云浮市| 文登市| 化州市| 德阳市| 垫江县| 南川市| 京山县| 会东县| 炉霍县| 景洪市| 长寿区| 南昌县| 团风县| 桦川县| 九江市| 游戏| 察哈|