Promise有各种开源实现,在ES6中被统一规范,由浏览器直接支持。最大的好处是在异步执行的流程中,把执行代码和处理结果的代码清晰地分离了.
Promise还可以做更多的事情,比如,有若干个异步任务,需要先做任务1,如果成功后再做任务2,任何任务失败则不再继续并执行错误处理函数。要串行执行这样的异步任务,不用Promise需要写一层一层的嵌套代码。
以下是其应用之一:随机生成0-5之间的数字,小于2时,立即停止,否则在数字秒数之后停止。
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Promise</title>
</head>
<body>
<div id='glc'> Promise 随机生成0-5之间的数字,小于2时,立即停止,否则在数字秒数之后停止。</div>
<div id='test1'> Promise </div>
<div id='test2'> Promise </div>
<div id='test3'> Promise </div>
scope.dispatchEvent is not a function at XMLHttpRequest.onloaded
<script>
'use strict';
// 清除log:
var logging = document.getElementsByTagName('body')[0];
while (logging.children.length > 1) {
logging.removeChild(logging.children[logging.children.length - 1]);
}
// 输出log到页面:
function log(s) {
var p = document.createElement('p');
p.innerHTML = s;
logging.appendChild(p);
}
new Promise(function (resolve, reject) {
log('start new Promise...');
var timeOut = Math.random() * 5;
log('set timeout to: ' + timeOut + ' seconds.');
setTimeout(function () {
if (timeOut < 2) {
log('call resolve()...');
resolve('小于2, OK');
}
else {
log('call reject()...');
reject('大于2,timeout in ' + timeOut + ' seconds.');
}
}, timeOut * 1000);
}).then(function (r) {
log('Done: ' + r);
}).catch(function (r) {
log('Failed: ' + r);
});
</script>
</body>
</html>
参考:https://www.liaoxuefeng.com/wiki/1022910821149312/1023024413276544