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

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.

主站蜘蛛池模板: 十堰市| 新郑市| 班戈县| 浦县| 土默特左旗| 舞钢市| 甘南县| 兴业县| 南投市| 漠河县| 婺源县| 普格县| 丰镇市| 广宁县| 湟中县| 维西| 平邑县| 彭山县| 北海市| 辰溪县| 石屏县| 保山市| 开江县| 修文县| 简阳市| 来凤县| 梓潼县| 郸城县| 襄樊市| 海宁市| 嵊州市| 中超| 容城县| 临颍县| 汽车| 屏东市| 清涧县| 江陵县| 沧州市| 泰兴市| 出国|