1var $fragments,camera,renderer,stripe,elements, isGA = false, donor = '',fouInit = false, grabbing = false,nameImage = null, donated = false; 2 3//var film = '<iframe src="https://player.vimeo.com/video/266135763?autoplay=1&title=0&byline=0&portrait=0" width="640" height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>' 4 5$(function() 6{ 7 $fragments = $('#fragments'); 8 if($fragments.length) 9 { 10 startFOU(); 11 12 13 } 14}) 15 16function startFOU() 17{ 18 $fragments = $('#fragments'); 19 $('.Site-foot').css('z-index',20); 20 $(window).resize(function() 21 { 22 $('.Fragments-overlay--film iframe').each(function() 23 { 24 var $t = $(this) 25 var $p = $t.parent(); 26 var w = $p.width(); 27 var ratio = $t.width() / $t.height() 28 console.log(ratio) 29 $t.width(w) 30 $t.height(w * ratio) 31 32 }) 33 34 if(fouInit) 35 { 36 camera.aspect = window.innerWidth / window.innerHeight; 37 38 if(window.innerWidth < 746) 39 { 40 camera.position.z = 350 41 } else { 42 camera.position.z = 300 43 } 44 camera.updateProjectionMatrix(); 45 46 renderer.setSize( window.innerWidth, window.innerHeight ); 47 } 48 49 }) 50 51 getCount() 52 initNav() 53 initStripe(); 54} 55 56function saveAsImage(renderer) { 57 var imgData, imgNode; 58 var strDownloadMime = "image/octet-stream"; 59 60 try { 61 var strMime = "image/jpeg"; 62 imgData = renderer.domElement.toDataURL(strMime); 63 64 65 $.post('/share/',{fragments: imgData,name: nameImage},function(res) 66 { 67 //saveFile('/share/' + res, res); 68 var time = res.replace('share.','').replace('.jpg',''); 69 70 $('#fbShare').attr('href',"http://www.facebook.com/sharer/sharer.php?s=100&p[title]=Wayne McGregor - Freespace&p[summary]=I%27ve%20just%20donated%20to%20the%20FreeSpace%20programme%20at%20%40StudioWayneMcGregor!%20Join%20us%20in%20giving%2015%2C000%20hours%20of%20space%20to%20artists%20and%20helping%20them%20to%20share%20their%20time%20and%20skills%20with%20others.%20%C2%A325%20gives%201%20hour%20of%20FreeSpace.%20%23WayneMcGregorFreeSpace&p[url]=https://waynemcgregor.com/freespace/?u=" + time) 71 72 $('#tShare').attr('href',"https://twitter.com/intent/tweet?text=I%27ve%20just%20donated%20to%20the%20FreeSpace%20programme%20at%20Studio%20%40WayneMcGregor!%20Join%20us%20in%20giving%2015%2C000%20hours%20of%20space%20to%20artists%20and%20helping%20them%20to%20share%20their%20time%20and%20skills%20with%20other.%20%C2%A325%20gives%201%20hour%20of%20FreeSpace%20%23WayneMcGregorFreeSpace&url=https://waynemcgregor.com/freespace/?u=" + time) 73 $('#shareImg').attr('src','/share/' + res) 74 $fragments.removeClass('about-is-active film-is-active donate-is-active').addClass('share-is-active'); 75 76 }); 77 $('.Grab canvas').remove() 78 //saveFile(imgData.replace(strMime, strDownloadMime), "FragmentsOfUs.jpg"); 79 80 } catch (e) { 81 console.log(e); 82 return; 83 } 84 85 } 86 87 function saveFile(strData, filename) { 88 var link = document.createElement('a'); 89 90 if (typeof link.download === 'string') { 91 document.body.appendChild(link); //Firefox requires the link to be in the body 92 link.download = filename; 93 link.href = strData; 94 link.click(); 95 document.body.removeChild(link); //remove the link when done 96 97 $('.Grab canvas').remove() 98 } else { 99 //window.location.replace(uri); 100 } 101 } 102 103function initStripe(){ 104 stripe = Stripe('pk_live_xLHGhqVc97S3OdzgW8Dc4Qzc'); 105 elements = stripe.elements(); 106 107 // Custom styling can be passed to options when creating an Element. 108 var style = { 109 110 base: { 111 // Add your base input styles here. For example: 112 font:{ 113 family:'Calibre Regular', 114 src: 'https://waynemcgregor.com/ui/fonts/Calibre-Regular.woff' 115 }, 116 fontSize: '17px', 117 color: "#FFFFFF", 118 border: '1px solid white' 119 } 120 }; 121 122 // Create an instance of the card Element. 123 var card = elements.create('card', {style: style}); 124 125 // Add an instance of the card Element into the `card-element` <div>. 126 card.mount('#card-element'); 127 128 card.addEventListener('change', function(event) { 129 var displayError = document.getElementById('card-errors'); 130 if (event.error) { 131 displayError.textContent = event.error.message; 132 } else { 133 displayError.textContent = ''; 134 } 135 }); 136 137 // Create a token or display an error when the form is submitted. 138 var form = document.getElementById('payment-form'); 139 form.addEventListener('submit', function(event) { 140 event.preventDefault(); 141 var hasErrors = false 142 143 $('.required').each(function() 144 { 145 if($(this).val() == '') 146 { 147 $(this).addClass('error') 148 hasErrors = true 149 } 150 }) 151 152 if(isGA) 153 { 154 $('.grequired').each(function() 155 { 156 if($(this).val() == '') 157 { 158 $(this).addClass('error') 159 hasErrors = true 160 } 161 }) 162 163 } 164 165 if(!hasErrors) { 166 167 $('#submit').text('Please wait') 168 169 stripe.createToken(card).then(function(result) { 170 if (result.error) { 171 // Inform the customer that there was an error. 172 var errorElement = document.getElementById('card-errors'); 173 errorElement.textContent = result.error.message; 174 } else { 175 // Send the token to your server.
176 stripeTokenHandler(result.token); 177 } 178 }); 179 180 } 181 }); 182} 183 184 185 186function stripeTokenHandler(token) { 187 // Insert the token ID into the form so it gets submitted to the server 188 var form = document.getElementById('payment-form'); 189 var hiddenInput = document.createElement('input'); 190 hiddenInput.setAttribute('type', 'hidden'); 191 hiddenInput.setAttribute('name', 'stripeToken'); 192 hiddenInput.setAttribute('value', token.id); 193 form.appendChild(hiddenInput); 194 195 196 197 // ajax submit 198 199 var data = $('#payment-form').serialize(); 200 201 $.ajax({ 202 type: 'POST', 203 url: '/actions/fragments/donate/', 204 data: data, 205 success: function(data){ 206 // your code from above 207 donor = form.name.value; 208 initDonation(donor) 209 }, 210 error: function(xhr, textStatus, error){ 211 alert('Sorry, there was a problem with your payment, please try again'); 212 $('#submit').text('Submit payment') 213 } 214 }); 215 216 217 218} 219 220function initDonation() 221{ 222 $('#donorName').text(donor) 223 var number = (totalDonations + 1).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ","); 224 var text = 'With your help we have reached hour<br>' + number + ' of 15,000'; 225 $('#donorNumber').html(text) 226 $('canvas').remove() 227 228 $('#donorNameCopy').text(donor) 229 $('#donorNumberCopy').html(' <br>'+number + " / 15,000") 230 231 $('.Fragments > h2').removeClass('is-visible') 232 233 234 setTimeout(function() 235 { 236 $('#donorNumber').fadeOut(function() 237 { 238 $(this).html(' <br>'+number + " / 15,000"); 239 $(this).fadeIn(); 240 $('#donate').text('Share') 241 donated = true 242 }) 243 }, 5000) 244 245 $fragments.removeClass('donate-is-active'); 246 $('.Fragment-donor').addClass('is-active'); 247 setTimeout(function() 248 { 249 initFOU(totalDonations + 1) 250 }, 5000) 251 252} 253 254function checkGA(el) 255{ 256 if(el.checked) { 257 $('.Address').show() 258 isGA = true; 259 } else { 260 $('.Address').hide() 261 isGA = false; 262 } 263} 264 265function checkAmount(el) 266{ 267 if(el.value == 0) 268 { 269 $('.form-row-customAmount').show(); 270 } else { 271 $('.form-row-customAmount').hide(); 272 } 273} 274 275function share() 276{ 277 grabbing = true 278 //$('.Fragment-donor-grab').css('z-index',300) 279 280 html2canvas(document.querySelector('.Fragment-donor-grab'), { backgroundColor: null, scale: 1.5 }).then(function(canvas) { 281 //$('.Fragment-donor-grab').css('z-index',1) 282 //document.body.appendChild(canvas); 283 nameImage = canvas.toDataURL("image/png"); 284 initGrab(totalDonations,nameImage) 285 286// var i = $('<img/>').attr('src',nameImage) 287// $('body').append(i) 288// i.css({ 289// 'position': 'absolute', 290// 'z-index':200, 291// top: 0 292// }) 293 }); 294} 295 296function initNav() 297{ 298 299 $('#grab').click(function() 300 { 301 //$fragments.addClass('share-is-active') 302 share(); 303 304 }); 305 306 $('.Fragments-navigation a').click(function() 307 { 308 $(this).parent().siblings().removeClass('is-active') 309 $(this).parent().addClass('is-active') 310 }) 311 312 $('.Fragments-overlay-close').click(function() 313 { 314 var cls = $(this).data('type') 315 $fragments.removeClass(cls) 316 $fragments.find('.Fragments-overlay--film iframe').remove() 317 $('.Fragments-navigation li').removeClass('is-active') 318 }) 319 320 $('#about').click(function() 321 { 322 if($fragments.hasClass('about-is-active')) return false; 323 $fragments.removeClass('film-is-active donate-is-active share-is-active').addClass('about-is-active'); 324 $fragments.find('.Fragments-overlay--film iframe').remove() 325 }) 326 $('#film').click(function() 327 { 328 if($fragments.hasClass('film-is-active')) return false; 329 330 $fragments.removeClass('about-is-active donate-is-active share-is-active').addClass('film-is-active'); 331 $fragments.find('.Fragments-overlay--film > div').append(film) 332 $(window).resize(); 333 }) 334 $('#donate').click(function() 335 { 336 if($fragments.hasClass('donate-is-active')) return false; 337 if(!donated) 338 { 339 $fragments.removeClass('about-is-active film-is-active').addClass('donate-is-active'); 340 } else { 341 342 share(); 343 } 344 345 346 }) 347} 348 349function getCount() 350{ 351 console.log('loading count') 352 353 $.ajax({ 354 url: '/json/fragments.json', 355 dataType: 'json', 356 success: function (json) { 357 console.log('data',json.count) 358 count = parseInt(json.count) 359 setTimeout(function() 360 { 361 initFOU(count) 362 363 setTimeout(function() 364 { 365 $('.Fragments > h1').addClass('is-hidden') 366 setTimeout(function() 367 { 368 $('.Fragments > h2').addClass('is-visible') 369 } 370 , 1000); 371 372 373 $('#film').click(); 374 },2000) 375 },1000) 376 377 } 378 }); 379} 380 381totalDonations = 0; 382 383function initFOU(complete) 384{ 385 console.log(grabbing) 386 totalDonations = complete 387 var wrapper = grabbing ? $('.Grab').get(0) : $fragments.get(0) 388 var scene = new THREE.Scene(); 389 var loader = new THREE.TextureLoader() 390 var particleTexture = loader.load('/ui/img/particle2.png') 391 var ambient = new THREE.AmbientLight( 0x101010 ); 392 var radius = 130; 393 var geometry = new THREE.Geometry(); 394 var particalCount = 15000 395 var particlesDelay = 0; 396 //var complete = 14000 397 var ratio = particalCount/(Math.PI) 398 var min = 360 399 var max = 360 - ((360 / particalCount) * complete) 400 401 // setup camera 402 camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 ); 403 404 renderer = new THREE.WebGLRenderer(); 405 renderer.setPixelRatio( window.devicePixelRatio ); 406 renderer.setSize( grabbing ? 1500 : window.innerWidth, grabbing ? 1500 : window.innerHeight ); 407 wrapper.appendChild( this.renderer.domElement ); 408 loader.crossOrigin = true; 409 410 for (var i = 0; i < complete; i++) { 411 412 var vertex = new THREE.Vector3(); 413 414 var diff = Math.random() * 40
415 var myRadius = radius + diff 416 //console.log(diff) 417 418 vertex.x = (myRadius * Math.cos(2 * Math.PI * i / particalCount)); 419 vertex.y = (myRadius * Math.sin(2 * Math.PI * i / particalCount)); 420 vertex.z = grabbing ? 0 : -800 421 422 vertex.start = { 423 x: vertex.x, 424 y: vertex.y, 425 diff: diff 426 } 427 428 vertex.rotationAxis = new THREE.Vector3(0.3, 0,2 ); 429 vertex.rotationAxis.normalize(); 430 vertex.delay = particlesDelay; 431 432 particlesDelay += 0.15 433 geometry.vertices.push(vertex); 434 } 435 436 var meshMaterial = new THREE.MeshPhongMaterial( { color: 0xFFFFFF, emissive: 0xFFFFFF, side: THREE.DoubleSide, flatShading: true, alphaMap: particleTexture } ); 437 var particles = new THREE.Points(geometry, new THREE.PointsMaterial({ 438 size: window.innerWidth < 746 ? 2.2 : 1.7, 439 color: 0xffffff, 440 map: particleTexture, 441 blending: THREE.AdditiveBlending, 442 transparent: true, opacity: 1})); 443 //var particles = new THREE.Points(geometry, meshMaterial); 444 particles.boundingSphere = 50; 445 particles.sortParticles = true; 446 447 //console.log(particles) 448 449 particles.rotation.z = Math.PI / 2 450 451 scene.add(particles); 452 453 454 455 var radius = 25, 456 segments = 64, 457 material = new THREE.LineBasicMaterial( { color: 0x999999, linewidth: 1 } ), 458 cMaterial = new THREE.MeshPhongMaterial( { color: 0x999999, emissive: 0x000000, side: THREE.DoubleSide, flatShading: true } ), 459 cGeometry = new THREE.CircleGeometry( radius, segments ); 460 461 462 cGeometry.vertices.shift(); 463 464 var bufferOutline = new THREE.BufferGeometry(); 465 cGeometry = bufferOutline.fromGeometry(cGeometry) 466 467 // Remove center vertex 468 geometry.vertices.shift(); 469 470 // Non closed circle with one open segment: 471 ///scene.add( new THREE.Line( geometry, material ) ); 472 473// To get a closed circle use LineLoop instead (see also @jackrugile his comment): 474 475 var outline = new THREE.LineLoop( cGeometry, material ) 476 var circle = new THREE.Mesh( cGeometry, cMaterial ) 477 //scene.add( circle ); 478 //scene.add(outline); 479 480 circle.position.z = 200 481 482 //scene.add( sphere ); 483 484 var l = new THREE.PointLight( 0xffffff, 1, 0 ); 485 l.position.set( 0, 200, 300 ); 486 scene.add(l) 487 488 camera.position.z = window.innerWidth < 746 ? 350 : 300; 489 var elapsed = 0 490 491 //console.log(particles) 492 493 var dist = 10 494 var count= 0 495 var dir = 0.1 496 var delay = 2 497 var elapsed = 0; 498 499 var init = false 500 501 var speed = Math.random * 1 502 503 var animate = function () { 504 requestAnimationFrame( animate ); 505 506 for (var i = 0, len = particles.geometry.vertices.length; i < len; i++) { 507 var v = particles.geometry.vertices[i] 508 v.y += Math.random() - 0.5 509 v.x += Math.random() - 0.5 510 //v.z += Math.random() - 0.5 511 512 //console.log(v.z) 513 514 if(elapsed > v.delay) 515 if(v.z < 0) v.z =0 516 } 517 /*particles.geometry.vertices.forEach(function(v){ 518 519 })*/ 520 521 522 elapsed++ 523 524 particles.geometry.verticesNeedUpdate = true; 525 526 //controls.update(); 527 528 renderer.render( scene, camera ); 529 530 //elapsed++ 531 }; 532 533 animate(); 534 fouInit = true; 535} 536 537grabbed = false 538 539function initGrab(complete,imgData) 540{ 541 var loops = 0 542 var grabbing = true 543 //totalDonations = complete 544 var wrapper = grabbing ? $('.Grab').get(0) : $fragments.get(0) 545 var scene = new THREE.Scene(); 546 var loader = new THREE.TextureLoader() 547 var particleTexture = loader.load('https://threejs.org/examples/textures/particle2.png') 548 var ambient = new THREE.AmbientLight( 0x101010 ); 549 var radius = 130; 550 var geometry = new THREE.Geometry(); 551 var particalCount = 15000 552 var particlesDelay = 0; 553 //var complete = 14000 554 var ratio = particalCount/(Math.PI) 555 var min = 360 556 var max = 360 - ((360 / particalCount) * complete) 557 558 // setup camera 559 var camera = new THREE.PerspectiveCamera( 75, 1, 0.1, 1000 ); 560 561 var renderer = new THREE.WebGLRenderer(); 562 renderer.setPixelRatio( 1 ); 563 renderer.setSize( grabbing ? 1000 : window.innerWidth, grabbing ? 1000 : window.innerHeight ); 564 wrapper.appendChild( renderer.domElement ); 565 loader.crossOrigin = true; 566 567 for (var i = 0; i < complete; i++) { 568 569 var vertex = new THREE.Vector3(); 570 571 var diff = Math.random() * 40
572 var myRadius = radius + diff 573 //console.log(diff) 574 575 vertex.x = (myRadius * Math.cos(2 * Math.PI * i / particalCount)); 576 vertex.y = (myRadius * Math.sin(2 * Math.PI * i / particalCount)); 577 vertex.z = grabbing ? 0 : -800 578 579 vertex.start = { 580 x: vertex.x, 581 y: vertex.y, 582 diff: diff 583 } 584 585 vertex.rotationAxis = new THREE.Vector3(0.3, 0,2 ); 586 vertex.rotationAxis.normalize(); 587 vertex.delay = particlesDelay; 588 589 particlesDelay += 0.15 590 geometry.vertices.push(vertex); 591 } 592 593 var meshMaterial = new THREE.MeshPhongMaterial( { color: 0xFFFFFF, emissive: 0xFFFFFF, side: THREE.DoubleSide, flatShading: true, alphaMap: particleTexture } ); 594 var particles = new THREE.Points(geometry, new THREE.PointsMaterial({ 595 size: window.innerWidth < 746 ? 2.2 : 1.7, 596 color: 0x666666, 597 map: particleTexture, 598 blending: THREE.AdditiveBlending, 599 transparent: true, opacity: 1})); 600 //var particles = new THREE.Points(geometry, meshMaterial); 601 particles.boundingSphere = 50; 602 particles.sortParticles = true; 603 604 //console.log(particles) 605 606 particles.rotation.z = Math.PI / 2 607 608 scene.add(particles); 609 610 611 var radius = 25, 612 segments = 64, 613 material = new THREE.LineBasicMaterial( { color: 0x999999, linewidth: 1 } ), 614 cMaterial = new THREE.MeshPhongMaterial( { color: 0x999999, emissive: 0x000000, side: THREE.DoubleSide, flatShading: true } ), 615 cGeometry = new THREE.CircleGeometry( radius, segments ); 616 617 618 cGeometry.vertices.shift(); 619 620 var bufferOutline = new THREE.BufferGeometry(); 621 cGeometry = bufferOutline.fromGeometry(cGeometry) 622 623 // Remove center vertex 624 geometry.vertices.shift(); 625 626 // Non closed circle with one open segment: 627 ///scene.add( new THREE.Line( geometry, material ) ); 628 629// To get a closed circle use LineLoop instead (see also @jackrugile his comment): 630 631 var outline = new THREE.LineLoop( cGeometry, material ) 632 var circle = new THREE.Mesh( cGeometry, cMaterial ) 633 //scene.add( circle ); 634 //scene.add(outline); 635 636 circle.position.z = 200 637 638 //scene.add( sphere ); 639 640 var l = new THREE.PointLight( 0xffffff, 1, 0 ); 641 l.position.set( 0, 200, 300 ); 642 scene.add(l) 643 644 camera.position.z = window.innerWidth < 746 ? 350 : 300; 645 var elapsed = 0 646 647 //console.log(particles) 648 649 var dist = 10 650 var count= 0 651 var dir = 0.1 652 var delay = 2 653 var elapsed = 0; 654 655 var init = false 656 657 var speed = Math.random * 1 658 659 var animate = function () { 660 requestAnimationFrame( animate ); 661 662 for (var i = 0, len = particles.geometry.vertices.length; i < len; i++) { 663 var v = particles.geometry.vertices[i] 664 v.y += Math.random() - 0.5 665 v.x += Math.random() - 0.5 666 //v.z += Math.random() - 0.5 667 668 //console.log(v.z) 669 670 if(elapsed > v.delay) 671 if(v.z < 0) v.z =0 672 } 673 674 /*particles.geometry.vertices.forEach(function(v){ 675 676 })*/ 677 678 679 elapsed++ 680 681 particles.geometry.verticesNeedUpdate = true; 682 683 //controls.update(); 684 685 renderer.render( scene, camera ); 686 687 if(!grabbed && loops > 20) { 688 saveAsImage(renderer) 689 grabbed = true 690 } 691 692 loops++; 693 694 //elapsed++ 695 }; 696 697 animate(); 698 fouInit = true; 699} 700 701/*! 702 * @overview es6-promise - a tiny implementation of Promises/A+. 703 * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) 704 * @license Licensed under MIT license 705 * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE 706 * @version v4.2.5+7f2b526d 707 */ 708 709(function (global, factory) { 710 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 711 typeof define === 'function' && define.amd ? define(factory) : 712 (global.ES6Promise = factory()); 713}(this, (function () { 'use strict'; 714 715function objectOrFunction(x) { 716 var type = typeof x; 717 return x !== null && (type === 'object' || type === 'function'); 718} 719 720function isFunction(x) { 721 return typeof x === 'function'; 722} 723 724 725 726var _isArray = void 0; 727if (Array.isArray) { 728 _isArray = Array.isArray; 729} else { 730 _isArray = function (x) { 731 return Object.prototype.toString.call(x) === '[object Array]'; 732 }; 733} 734 735var isArray = _isArray; 736 737var len = 0; 738var vertxNext = void 0; 739var customSchedulerFn = void 0; 740 741var asap = function asap(callback, arg) { 742 queue[len] = callback; 743 queue[len + 1] = arg;
vendor: 2,974 bytes, lines 744-855
744 len += 2; 745 if (len === 2) { 746 // If len is 2, that means that we need to schedule an async flush. 747 // If additional callbacks are queued before the queue is flushed, they 748 // will be processed by this flush that we are scheduling. 749 if (customSchedulerFn) { 750 customSchedulerFn(flush); 751 } else { 752 scheduleFlush(); 753 } 754 } 755}; 756 757function setScheduler(scheduleFn) { 758 customSchedulerFn = scheduleFn; 759} 760 761function setAsap(asapFn) { 762 asap = asapFn; 763} 764 765var browserWindow = typeof window !== 'undefined' ? window : undefined; 766var browserGlobal = browserWindow || {}; 767var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; 768var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; 769 770// test for web worker but not in IE10 771var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; 772 773// node 774function useNextTick() { 775 // node version 0.10.x displays a deprecation warning when nextTick is used recursively 776 // see https://github.com/cujojs/when/issues/410 for details 777 return function () { 778 return process.nextTick(flush); 779 }; 780} 781 782// vertx 783function useVertxTimer() { 784 if (typeof vertxNext !== 'undefined') { 785 return function () { 786 vertxNext(flush); 787 }; 788 } 789 790 return useSetTimeout(); 791} 792 793function useMutationObserver() { 794 var iterations = 0; 795 var observer = new BrowserMutationObserver(flush); 796 var node = document.createTextNode(''); 797 observer.observe(node, { characterData: true }); 798 799 return function () { 800 node.data = iterations = ++iterations % 2; 801 }; 802} 803 804// web worker 805function useMessageChannel() { 806 var channel = new MessageChannel(); 807 channel.port1.onmessage = flush; 808 return function () { 809 return channel.port2.postMessage(0); 810 }; 811} 812 813function useSetTimeout() { 814 // Store setTimeout reference so es6-promise will be unaffected by 815 // other code modifying setTimeout (like sinon.useFakeTimers()) 816 var globalSetTimeout = setTimeout; 817 return function () { 818 return globalSetTimeout(flush, 1); 819 }; 820} 821 822var queue = new Array(1000); 823function flush() { 824 for (var i = 0; i < len; i += 2) { 825 var callback = queue[i]; 826 var arg = queue[i + 1]; 827 828 callback(arg); 829 830 queue[i] = undefined; 831 queue[i + 1] = undefined; 832 } 833 834 len = 0; 835} 836 837function attemptVertx() { 838 try { 839 var vertx = Function('return this')().require('vertx'); 840 vertxNext = vertx.runOnLoop || vertx.runOnContext; 841 return useVertxTimer(); 842 } catch (e) { 843 return useSetTimeout(); 844 } 845} 846 847var scheduleFlush = void 0; 848// Decide what async method to use to triggering processing of queued callbacks: 849if (isNode) { 850 scheduleFlush = useNextTick(); 851} else if (BrowserMutationObserver) { 852 scheduleFlush = useMutationObserver(); 853} else if (isWorker) { 854 scheduleFlush = useMessageChannel(); 855} else if (browserWindow === undefined && typeof require
vendor: 8,555 bytes, lines 855-1232
855 === 'function') { 856 scheduleFlush = attemptVertx(); 857} else { 858 scheduleFlush = useSetTimeout(); 859} 860 861function then(onFulfillment, onRejection) { 862 var parent = this; 863 864 var child = new this.constructor(noop); 865 866 if (child[PROMISE_ID] === undefined) { 867 makePromise(child); 868 } 869 870 var _state = parent._state; 871 872 873 if (_state) { 874 var callback = arguments[_state - 1]; 875 asap(function () { 876 return invokeCallback(_state, child, callback, parent._result); 877 }); 878 } else { 879 subscribe(parent, child, onFulfillment, onRejection); 880 } 881 882 return child; 883} 884 885/** 886 `Promise.resolve` returns a promise that will become resolved with the 887 passed `value`. It is shorthand for the following: 888 889 ```javascript 890 let promise = new Promise(function(resolve, reject){ 891 resolve(1); 892 }); 893 894 promise.then(function(value){ 895 // value === 1 896 }); 897 ``` 898 899 Instead of writing the above, your code now simply becomes the following: 900 901 ```javascript 902 let promise = Promise.resolve(1); 903 904 promise.then(function(value){ 905 // value === 1 906 }); 907 ``` 908 909 @method resolve 910 @static 911 @param {Any} value value that the returned promise will be resolved with 912 Useful for tooling. 913 @return {Promise} a promise that will become fulfilled with the given 914 `value` 915*/ 916function resolve$1(object) { 917 /*jshint validthis:true */ 918 var Constructor = this; 919 920 if (object && typeof object === 'object' && object.constructor === Constructor) { 921 return object; 922 } 923 924 var promise = new Constructor(noop); 925 resolve(promise, object); 926 return promise; 927} 928 929var PROMISE_ID = Math.random().toString(36).substring(2); 930 931function noop() {} 932 933var PENDING = void 0; 934var FULFILLED = 1; 935var REJECTED = 2; 936 937var TRY_CATCH_ERROR = { error: null }; 938 939function selfFulfillment() { 940 return new TypeError("You cannot resolve a promise with itself"); 941} 942 943function cannotReturnOwn() { 944 return new TypeError('A promises callback cannot return that same promise.'); 945} 946 947function getThen(promise) { 948 try { 949 return promise.then; 950 } catch (error) { 951 TRY_CATCH_ERROR.error = error; 952 return TRY_CATCH_ERROR; 953 } 954} 955 956function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { 957 try { 958 then$$1.call(value, fulfillmentHandler, rejectionHandler); 959 } catch (e) { 960 return e; 961 } 962} 963 964function handleForeignThenable(promise, thenable, then$$1) { 965 asap(function (promise) { 966 var sealed = false; 967 var error = tryThen(then$$1, thenable, function (value) { 968 if (sealed) { 969 return; 970 } 971 sealed = true; 972 if (thenable !== value) { 973 resolve(promise, value); 974 } else { 975 fulfill(promise, value); 976 } 977 }, function (reason) { 978 if (sealed) { 979 return; 980 } 981 sealed = true; 982 983 reject(promise, reason); 984 }, 'Settle: ' + (promise._label || ' unknown promise')); 985 986 if (!sealed && error) { 987 sealed = true; 988 reject(promise, error); 989 } 990 }, promise); 991} 992 993function handleOwnThenable(promise, thenable) { 994 if (thenable._state === FULFILLED) { 995 fulfill(promise, thenable._result); 996 } else if (thenable._state === REJECTED) { 997 reject(promise, thenable._result); 998 } else { 999 subscribe(thenable, undefined, function (value) { 1000 return resolve(promise, value); 1001 }, function (reason) { 1002 return reject(promise, reason); 1003 }); 1004 } 1005} 1006 1007function handleMaybeThenable(promise, maybeThenable, then$$1) { 1008 if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { 1009 handleOwnThenable(promise, maybeThenable); 1010 } else { 1011 if (then$$1 === TRY_CATCH_ERROR) { 1012 reject(promise, TRY_CATCH_ERROR.error); 1013 TRY_CATCH_ERROR.error = null; 1014 } else if (then$$1 === undefined) { 1015 fulfill(promise, maybeThenable); 1016 } else if (isFunction(then$$1)) { 1017 handleForeignThenable(promise, maybeThenable, then$$1); 1018 } else { 1019 fulfill(promise, maybeThenable); 1020 } 1021 } 1022} 1023 1024function resolve(promise, value) { 1025 if (promise === value) { 1026 reject(promise, selfFulfillment()); 1027 } else if (objectOrFunction(value)) { 1028 handleMaybeThenable(promise, value, getThen(value)); 1029 } else { 1030 fulfill(promise, value); 1031 } 1032} 1033 1034function publishRejection(promise) { 1035 if (promise._onerror) { 1036 promise._onerror(promise._result); 1037 } 1038 1039 publish(promise); 1040} 1041 1042function fulfill(promise, value) { 1043 if (promise._state !== PENDING) { 1044 return; 1045 } 1046 1047 promise._result = value; 1048 promise._state = FULFILLED; 1049 1050 if (promise._subscribers.length !== 0) { 1051 asap(publish, promise); 1052 } 1053} 1054 1055function reject(promise, reason) { 1056 if (promise._state !== PENDING) { 1057 return; 1058 } 1059 promise._state = REJECTED; 1060 promise._result = reason; 1061 1062 asap(publishRejection, promise); 1063} 1064 1065function subscribe(parent, child, onFulfillment, onRejection) { 1066 var _subscribers = parent._subscribers; 1067 var length = _subscribers.length; 1068 1069 1070 parent._onerror = null; 1071 1072 _subscribers[length] = child; 1073 _subscribers[length + FULFILLED] = onFulfillment; 1074 _subscribers[length + REJECTED] = onRejection; 1075 1076 if (length === 0 && parent._state) { 1077 asap(publish, parent); 1078 } 1079} 1080 1081function publish(promise) { 1082 var subscribers = promise._subscribers; 1083 var settled = promise._state; 1084 1085 if (subscribers.length === 0) { 1086 return; 1087 } 1088 1089 var child = void 0, 1090 callback = void 0, 1091 detail = promise._result; 1092 1093 for (var i = 0; i < subscribers.length; i += 3) { 1094 child = subscribers[i]; 1095 callback = subscribers[i + settled]; 1096 1097 if (child) { 1098 invokeCallback(settled, child, callback, detail); 1099 } else { 1100 callback(detail); 1101 } 1102 } 1103 1104 promise._subscribers.length = 0; 1105} 1106 1107function tryCatch(callback, detail) { 1108 try { 1109 return callback(detail); 1110 } catch (e) { 1111 TRY_CATCH_ERROR.error = e; 1112 return TRY_CATCH_ERROR; 1113 } 1114} 1115 1116function invokeCallback(settled, promise, callback, detail) { 1117 var hasCallback = isFunction(callback), 1118 value = void 0, 1119 error = void 0, 1120 succeeded = void 0, 1121 failed = void 0; 1122 1123 if (hasCallback) { 1124 value = tryCatch(callback, detail); 1125 1126 if (value === TRY_CATCH_ERROR) { 1127 failed = true; 1128 error = value.error; 1129 value.error = null; 1130 } else { 1131 succeeded = true; 1132 } 1133 1134 if (promise === value) { 1135 reject(promise, cannotReturnOwn()); 1136 return; 1137 } 1138 } else { 1139 value = detail; 1140 succeeded = true; 1141 } 1142 1143 if (promise._state !== PENDING) { 1144 // noop 1145 } else if (hasCallback && succeeded) { 1146 resolve(promise, value); 1147 } else if (failed) { 1148 reject(promise, error); 1149 } else if (settled === FULFILLED) { 1150 fulfill(promise, value); 1151 } else if (settled === REJECTED) { 1152 reject(promise, value); 1153 } 1154} 1155 1156function initializePromise(promise, resolver) { 1157 try { 1158 resolver(function resolvePromise(value) { 1159 resolve(promise, value); 1160 }, function rejectPromise(reason) { 1161 reject(promise, reason); 1162 }); 1163 } catch (e) { 1164 reject(promise, e); 1165 } 1166} 1167 1168var id = 0; 1169function nextId() { 1170 return id++; 1171} 1172 1173function makePromise(promise) { 1174 promise[PROMISE_ID] = id++; 1175 promise._state = undefined; 1176 promise._result = undefined; 1177 promise._subscribers = []; 1178} 1179 1180function validationError() { 1181 return new Error('Array Methods must be provided an Array'); 1182} 1183 1184var Enumerator = function () { 1185 function Enumerator(Constructor, input) { 1186 this._instanceConstructor = Constructor; 1187 this.promise = new Constructor(noop); 1188 1189 if (!this.promise[PROMISE_ID]) { 1190 makePromise(this.promise); 1191 } 1192 1193 if (isArray(input)) { 1194 this.length = input.length; 1195 this._remaining = input.length; 1196 1197 this._result = new Array(this.length); 1198 1199 if (this.length === 0) { 1200 fulfill(this.promise, this._result); 1201 } else { 1202 this.length = this.length || 0; 1203 this._enumerate(input); 1204 if (this._remaining === 0) { 1205 fulfill(this.promise, this._result); 1206 } 1207 } 1208 } else { 1209 reject(this.promise, validationError()); 1210 } 1211 } 1212 1213 Enumerator.prototype._enumerate = function _enumerate(input) { 1214 for (var i = 0; this._state === PENDING && i < input.length; i++) { 1215 this._eachEntry(input[i], i); 1216 } 1217 }; 1218 1219 Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { 1220 var c = this._instanceConstructor; 1221 var resolve$$1 = c.resolve; 1222 1223 1224 if (resolve$$1 === resolve$1) { 1225 var _then = getThen(entry); 1226 1227 if (_then === then && entry._state !== PENDING) { 1228 this._settledAt(entry._state, i, entry._result); 1229 } else if (typeof _then !== 'function') { 1230 this._remaining--; 1231 this._result[i] = entry; 1232 } else if (c === Promise$
12322) { 1233 var promise = new c(noop); 1234 handleMaybeThenable(promise, entry, _then);
vendor: 6,040 bytes, lines 1234-1459
1234 1235 this._willSettleAt(promise, i); 1236 } else { 1237 this._willSettleAt(new c(function (resolve$$1) { 1238 return resolve$$1(entry); 1239 }), i); 1240 } 1241 } else { 1242 this._willSettleAt(resolve$$1(entry), i); 1243 } 1244 }; 1245 1246 Enumerator.prototype._settledAt = function _settledAt(state, i, value) { 1247 var promise = this.promise; 1248 1249 1250 if (promise._state === PENDING) { 1251 this._remaining--; 1252 1253 if (state === REJECTED) { 1254 reject(promise, value); 1255 } else { 1256 this._result[i] = value; 1257 } 1258 } 1259 1260 if (this._remaining === 0) { 1261 fulfill(promise, this._result); 1262 } 1263 }; 1264 1265 Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { 1266 var enumerator = this; 1267 1268 subscribe(promise, undefined, function (value) { 1269 return enumerator._settledAt(FULFILLED, i, value); 1270 }, function (reason) { 1271 return enumerator._settledAt(REJECTED, i, reason); 1272 }); 1273 }; 1274 1275 return Enumerator; 1276}(); 1277 1278/** 1279 `Promise.all` accepts an array of promises, and returns a new promise which 1280 is fulfilled with an array of fulfillment values for the passed promises, or 1281 rejected with the reason of the first passed promise to be rejected. It casts all 1282 elements of the passed iterable to promises as it runs this algorithm. 1283 1284 Example: 1285 1286 ```javascript 1287 let promise1 = resolve(1); 1288 let promise2 = resolve(2); 1289 let promise3 = resolve(3); 1290 let promises = [ promise1, promise2, promise3 ]; 1291 1292 Promise.all(promises).then(function(array){ 1293 // The array here would be [ 1, 2, 3 ]; 1294 }); 1295 ``` 1296 1297 If any of the `promises` given to `all` are rejected, the first promise 1298 that is rejected will be given as an argument to the returned promises's 1299 rejection handler. For example: 1300 1301 Example: 1302 1303 ```javascript 1304 let promise1 = resolve(1); 1305 let promise2 = reject(new Error("2")); 1306 let promise3 = reject(new Error("3")); 1307 let promises = [ promise1, promise2, promise3 ]; 1308 1309 Promise.all(promises).then(function(array){ 1310 // Code here never runs because there are rejected promises! 1311 }, function(error) { 1312 // error.message === "2" 1313 }); 1314 ``` 1315 1316 @method all 1317 @static 1318 @param {Array} entries array of promises 1319 @param {String} label optional string for labeling the promise. 1320 Useful for tooling. 1321 @return {Promise} promise that is fulfilled when all `promises` have been 1322 fulfilled, or rejected if any of them become rejected. 1323 @static 1324*/ 1325function all(entries) { 1326 return new Enumerator(this, entries).promise; 1327} 1328 1329/** 1330 `Promise.race` returns a new promise which is settled in the same way as the 1331 first passed promise to settle. 1332 1333 Example: 1334 1335 ```javascript 1336 let promise1 = new Promise(function(resolve, reject){ 1337 setTimeout(function(){ 1338 resolve('promise 1'); 1339 }, 200); 1340 }); 1341 1342 let promise2 = new Promise(function(resolve, reject){ 1343 setTimeout(function(){ 1344 resolve('promise 2'); 1345 }, 100); 1346 }); 1347 1348 Promise.race([promise1, promise2]).then(function(result){ 1349 // result === 'promise 2' because it was resolved before promise1 1350 // was resolved. 1351 }); 1352 ``` 1353 1354 `Promise.race` is deterministic in that only the state of the first 1355 settled promise matters. For example, even if other promises given to the 1356 `promises` array argument are resolved, but the first settled promise has 1357 become rejected before the other promises became fulfilled, the returned 1358 promise will become rejected: 1359 1360 ```javascript 1361 let promise1 = new Promise(function(resolve, reject){ 1362 setTimeout(function(){ 1363 resolve('promise 1'); 1364 }, 200); 1365 }); 1366 1367 let promise2 = new Promise(function(resolve, reject){ 1368 setTimeout(function(){ 1369 reject(new Error('promise 2')); 1370 }, 100); 1371 }); 1372 1373 Promise.race([promise1, promise2]).then(function(result){ 1374 // Code here never runs 1375 }, function(reason){ 1376 // reason.message === 'promise 2' because promise 2 became rejected before 1377 // promise 1 became fulfilled 1378 }); 1379 ``` 1380 1381 An example real-world use case is implementing timeouts: 1382 1383 ```javascript 1384 Promise.race([ajax('foo.json'), timeout(5000)]) 1385 ``` 1386 1387 @method race 1388 @static 1389 @param {Array} promises array of promises to observe 1390 Useful for tooling. 1391 @return {Promise} a promise which settles in the same way as the first passed 1392 promise to settle. 1393*/ 1394function race(entries) { 1395 /*jshint validthis:true */ 1396 var Constructor = this; 1397 1398 if (!isArray(entries)) { 1399 return new Constructor(function (_, reject) { 1400 return reject(new TypeError('You must pass an array to race.')); 1401 }); 1402 } else { 1403 return new Constructor(function (resolve, reject) { 1404 var length = entries.length; 1405 for (var i = 0; i < length; i++) { 1406 Constructor.resolve(entries[i]).then(resolve, reject); 1407 } 1408 }); 1409 } 1410} 1411 1412/** 1413 `Promise.reject` returns a promise rejected with the passed `reason`. 1414 It is shorthand for the following: 1415 1416 ```javascript 1417 let promise = new Promise(function(resolve, reject){ 1418 reject(new Error('WHOOPS')); 1419 }); 1420 1421 promise.then(function(value){ 1422 // Code here doesn't run because the promise is rejected! 1423 }, function(reason){ 1424 // reason.message === 'WHOOPS' 1425 }); 1426 ``` 1427 1428 Instead of writing the above, your code now simply becomes the following: 1429 1430 ```javascript 1431 let promise = Promise.reject(new Error('WHOOPS')); 1432 1433 promise.then(function(value){ 1434 // Code here doesn't run because the promise is rejected! 1435 }, function(reason){ 1436 // reason.message === 'WHOOPS' 1437 }); 1438 ``` 1439 1440 @method reject 1441 @static 1442 @param {Any} reason value that the returned promise will be rejected with. 1443 Useful for tooling. 1444 @return {Promise} a promise rejected with the given `reason`. 1445*/ 1446function reject$1(reason) { 1447 /*jshint validthis:true */ 1448 var Constructor = this; 1449 var promise = new Constructor(noop); 1450 reject(promise, reason); 1451 return promise; 1452} 1453 1454function needsResolver() { 1455 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); 1456} 1457 1458function needsNew() { 1459 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object c
vendor: 10,575 bytes, lines 1459-1885
1459onstructor cannot be called as a function."); 1460} 1461 1462/** 1463 Promise objects represent the eventual result of an asynchronous operation. The 1464 primary way of interacting with a promise is through its `then` method, which 1465 registers callbacks to receive either a promise's eventual value or the reason 1466 why the promise cannot be fulfilled. 1467 1468 Terminology 1469 ----------- 1470 1471 - `promise` is an object or function with a `then` method whose behavior conforms to this specification. 1472 - `thenable` is an object or function that defines a `then` method. 1473 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). 1474 - `exception` is a value that is thrown using the throw statement. 1475 - `reason` is a value that indicates why a promise was rejected. 1476 - `settled` the final resting state of a promise, fulfilled or rejected. 1477 1478 A promise can be in one of three states: pending, fulfilled, or rejected. 1479 1480 Promises that are fulfilled have a fulfillment value and are in the fulfilled 1481 state. Promises that are rejected have a rejection reason and are in the 1482 rejected state. A fulfillment value is never a thenable. 1483 1484 Promises can also be said to *resolve* a value. If this value is also a 1485 promise, then the original promise's settled state will match the value's 1486 settled state. So a promise that *resolves* a promise that rejects will 1487 itself reject, and a promise that *resolves* a promise that fulfills will 1488 itself fulfill. 1489 1490 1491 Basic Usage: 1492 ------------ 1493 1494 ```js 1495 let promise = new Promise(function(resolve, reject) { 1496 // on success 1497 resolve(value); 1498 1499 // on failure 1500 reject(reason); 1501 }); 1502 1503 promise.then(function(value) { 1504 // on fulfillment 1505 }, function(reason) { 1506 // on rejection 1507 }); 1508 ``` 1509 1510 Advanced Usage: 1511 --------------- 1512 1513 Promises shine when abstracting away asynchronous interactions such as 1514 `XMLHttpRequest`s. 1515 1516 ```js 1517 function getJSON(url) { 1518 return new Promise(function(resolve, reject){ 1519 let xhr = new XMLHttpRequest(); 1520 1521 xhr.open('GET', url); 1522 xhr.onreadystatechange = handler; 1523 xhr.responseType = 'json'; 1524 xhr.setRequestHeader('Accept', 'application/json'); 1525 xhr.send(); 1526 1527 function handler() { 1528 if (this.readyState === this.DONE) { 1529 if (this.status === 200) { 1530 resolve(this.response); 1531 } else { 1532 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); 1533 } 1534 } 1535 }; 1536 }); 1537 } 1538 1539 getJSON('/posts.json').then(function(json) { 1540 // on fulfillment 1541 }, function(reason) { 1542 // on rejection 1543 }); 1544 ``` 1545 1546 Unlike callbacks, promises are great composable primitives. 1547 1548 ```js 1549 Promise.all([ 1550 getJSON('/posts'), 1551 getJSON('/comments') 1552 ]).then(function(values){ 1553 values[0] // => postsJSON 1554 values[1] // => commentsJSON 1555 1556 return values; 1557 }); 1558 ``` 1559 1560 @class Promise 1561 @param {Function} resolver 1562 Useful for tooling. 1563 @constructor 1564*/ 1565 1566var Promise$2 = function () { 1567 function Promise(resolver) { 1568 this[PROMISE_ID] = nextId(); 1569 this._result = this._state = undefined; 1570 this._subscribers = []; 1571 1572 if (noop !== resolver) { 1573 typeof resolver !== 'function' && needsResolver(); 1574 this instanceof Promise ? initializePromise(this, resolver) : needsNew(); 1575 } 1576 } 1577 1578 /** 1579 The primary way of interacting with a promise is through its `then` method, 1580 which registers callbacks to receive either a promise's eventual value or the 1581 reason why the promise cannot be fulfilled. 1582 ```js 1583 findUser().then(function(user){ 1584 // user is available 1585 }, function(reason){ 1586 // user is unavailable, and you are given the reason why 1587 }); 1588 ``` 1589 Chaining 1590 -------- 1591 The return value of `then` is itself a promise. This second, 'downstream' 1592 promise is resolved with the return value of the first promise's fulfillment 1593 or rejection handler, or rejected if the handler throws an exception. 1594 ```js 1595 findUser().then(function (user) { 1596 return user.name; 1597 }, function (reason) { 1598 return 'default name'; 1599 }).then(function (userName) { 1600 // If `findUser` fulfilled, `userName` will be the user's name, otherwise it 1601 // will be `'default name'` 1602 }); 1603 findUser().then(function (user) { 1604 throw new Error('Found user, but still unhappy'); 1605 }, function (reason) { 1606 throw new Error('`findUser` rejected and we're unhappy'); 1607 }).then(function (value) { 1608 // never reached 1609 }, function (reason) { 1610 // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. 1611 // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. 1612 }); 1613 ``` 1614 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. 1615 ```js 1616 findUser().then(function (user) { 1617 throw new PedagogicalException('Upstream error'); 1618 }).then(function (value) { 1619 // never reached 1620 }).then(function (value) { 1621 // never reached 1622 }, function (reason) { 1623 // The `PedgagocialException` is propagated all the way down to here 1624 }); 1625 ``` 1626 Assimilation 1627 ------------ 1628 Sometimes the value you want to propagate to a downstream promise can only be 1629 retrieved asynchronously. This can be achieved by returning a promise in the 1630 fulfillment or rejection handler. The downstream promise will then be pending 1631 until the returned promise is settled. This is called *assimilation*. 1632 ```js 1633 findUser().then(function (user) { 1634 return findCommentsByAuthor(user); 1635 }).then(function (comments) { 1636 // The user's comments are now available 1637 }); 1638 ``` 1639 If the assimliated promise rejects, then the downstream promise will also reject. 1640 ```js 1641 findUser().then(function (user) { 1642 return findCommentsByAuthor(user); 1643 }).then(function (comments) { 1644 // If `findCommentsByAuthor` fulfills, we'll have the value here 1645 }, function (reason) { 1646 // If `findCommentsByAuthor` rejects, we'll have the reason here 1647 }); 1648 ``` 1649 Simple Example 1650 -------------- 1651 Synchronous Example 1652 ```javascript 1653 let result; 1654 try { 1655 result = findResult(); 1656 // success 1657 } catch(reason) { 1658 // failure 1659 } 1660 ``` 1661 Errback Example 1662 ```js 1663 findResult(function(result, err){ 1664 if (err) { 1665 // failure 1666 } else { 1667 // success 1668 } 1669 }); 1670 ``` 1671 Promise Example; 1672 ```javascript 1673 findResult().then(function(result){ 1674 // success 1675 }, function(reason){ 1676 // failure 1677 }); 1678 ``` 1679 Advanced Example 1680 -------------- 1681 Synchronous Example 1682 ```javascript 1683 let author, books; 1684 try { 1685 author = findAuthor(); 1686 books = findBooksByAuthor(author); 1687 // success 1688 } catch(reason) { 1689 // failure 1690 } 1691 ``` 1692 Errback Example 1693 ```js 1694 function foundBooks(books) { 1695 } 1696 function failure(reason) { 1697 } 1698 findAuthor(function(author, err){ 1699 if (err) { 1700 failure(err); 1701 // failure 1702 } else { 1703 try { 1704 findBoooksByAuthor(author, function(books, err) { 1705 if (err) { 1706 failure(err); 1707 } else { 1708 try { 1709 foundBooks(books); 1710 } catch(reason) { 1711 failure(reason); 1712 } 1713 } 1714 }); 1715 } catch(error) { 1716 failure(err); 1717 } 1718 // success 1719 } 1720 }); 1721 ``` 1722 Promise Example; 1723 ```javascript 1724 findAuthor(). 1725 then(findBooksByAuthor). 1726 then(function(books){ 1727 // found books 1728 }).catch(function(reason){ 1729 // something went wrong 1730 }); 1731 ``` 1732 @method then 1733 @param {Function} onFulfilled 1734 @param {Function} onRejected 1735 Useful for tooling. 1736 @return {Promise} 1737 */ 1738 1739 /** 1740 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same 1741 as the catch block of a try/catch statement. 1742 ```js 1743 function findAuthor(){ 1744 throw new Error('couldn't find that author'); 1745 } 1746 // synchronous 1747 try { 1748 findAuthor(); 1749 } catch(reason) { 1750 // something went wrong 1751 } 1752 // async with promises 1753 findAuthor().catch(function(reason){ 1754 // something went wrong 1755 }); 1756 ``` 1757 @method catch 1758 @param {Function} onRejection 1759 Useful for tooling. 1760 @return {Promise} 1761 */ 1762 1763 1764 Promise.prototype.catch = function _catch(onRejection) { 1765 return this.then(null, onRejection); 1766 }; 1767 1768 /** 1769 `finally` will be invoked regardless of the promise's fate just as native 1770 try/catch/finally behaves 1771 1772 Synchronous example: 1773 1774 ```js 1775 findAuthor() { 1776 if (Math.random() > 0.5) { 1777 throw new Error(); 1778 } 1779 return new Author(); 1780 } 1781 1782 try { 1783 return findAuthor(); // succeed or fail 1784 } catch(error) { 1785 return findOtherAuther(); 1786 } finally { 1787 // always runs 1788 // doesn't affect the return value 1789 } 1790 ``` 1791 1792 Asynchronous example: 1793 1794 ```js 1795 findAuthor().catch(function(reason){ 1796 return findOtherAuther(); 1797 }).finally(function(){ 1798 // author was either found, or not 1799 }); 1800 ``` 1801 1802 @method finally 1803 @param {Function} callback 1804 @return {Promise} 1805 */ 1806 1807 1808 Promise.prototype.finally = function _finally(callback) { 1809 var promise = this; 1810 var constructor = promise.constructor; 1811 1812 if (isFunction(callback)) { 1813 return promise.then(function (value) { 1814 return constructor.resolve(callback()).then(function () { 1815 return value; 1816 }); 1817 }, function (reason) { 1818 return constructor.resolve(callback()).then(function () { 1819 throw reason; 1820 }); 1821 }); 1822 } 1823 1824 return promise.then(callback, callback); 1825 }; 1826 1827 return Promise; 1828}(); 1829 1830Promise$2.prototype.then = then; 1831Promise$2.all = all; 1832Promise$2.race = race; 1833Promise$2.resolve = resolve$1; 1834Promise$2.reject = reject$1; 1835Promise$2._setScheduler = setScheduler; 1836Promise$2._setAsap = setAsap; 1837Promise$2._asap = asap; 1838 1839/*global self*/ 1840function polyfill() { 1841 var local = void 0; 1842 1843 if (typeof global !== 'undefined') { 1844 local = global; 1845 } else if (typeof self !== 'undefined') { 1846 local = self; 1847 } else { 1848 try { 1849 local = Function('return this')(); 1850 } catch (e) { 1851 throw new Error('polyfill failed because global object is unavailable in this environment'); 1852 } 1853 } 1854 1855 var P = local.Promise; 1856 1857 if (P) { 1858 var promiseToString = null; 1859 try { 1860 promiseToString = Object.prototype.toString.call(P.resolve()); 1861 } catch (e) { 1862 // silently ignored 1863 } 1864 1865 if (promiseToString === '[object Promise]' && !P.cast) { 1866 return; 1867 } 1868 } 1869 1870 local.Promise = Promise$2; 1871} 1872 1873// Strange compat.. 1874Promise$2.polyfill = polyfill; 1875Promise$2.Promise = Promise$2; 1876 1877Promise$2.polyfill(); 1878 1879return Promise$2; 1880 1881}))); 1882 1883 1884 1885//# sourceMappingURL=es6-promise.auto.map
1886
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.