<div> <button id="test-promise-log">log</button> </div> <script> var logging = document.getElementById('test-promise-log'); while (logging.children.length > 1) { logging.removeChild(logging.children[logging.children.length - 1]); }
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() * 2; log('set timeout to: ' + timeOut + 'seconds.'); setTimeout(function() { if (timeOut < 1) { log('call resolve()... '); resolve('200 OK '); } else { log('call reject()...'); reject('timeout in ' + timeOut + ' seconds.'); } }, timeOut * 1000); }).then(function(r) { log('Done: ' + r); return new Promise(function(resolve, reject) { log('Done2: ' + r); resolve('300 OK '); }); }).catch(function(reason) { log('Failed: ' + reason); return new Promise(function(resolve, reject) { log('Failed2: ' + reason); reject('timeout in ' + timeOut + ' seconds.'); }); }).then(function(r) { log('Done3: ' + r); }).catch(function(reason) { log('Failed3: ' + reason); }); </script>
附上promise的其他参考:http://wiki.jikexueyuan.com/project/es6/promise.html
catch里就不用返回promise了 不然很蠢
Sign in to make a reply
杨子皓CDU
<div> <button id="test-promise-log">log</button> </div> <script> var logging = document.getElementById('test-promise-log'); while (logging.children.length > 1) { logging.removeChild(logging.children[logging.children.length - 1]); }