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

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.

主站蜘蛛池模板: 二手房| 方正县| 瑞安市| 五莲县| 泸溪县| 蕲春县| 桂林市| 蓬溪县| 理塘县| 康马县| 泾川县| 封开县| 稷山县| 夹江县| 绵阳市| 蒙阴县| 乌拉特中旗| 额敏县| 张家界市| 安溪县| 吉木萨尔县| 改则县| 南靖县| 吴桥县| 太康县| 黄龙县| 莱阳市| 吴忠市| 枞阳县| 田林县| 绥阳县| 浪卡子县| 雅安市| 永寿县| 迁西县| 莫力| 盘山县| 兰溪市| 泰和县| 辉县市| 怀宁县|