UNPKG

ask-for-promise

Version:
2 lines (1 loc) 1.72 kB
!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):(e="undefined"!=typeof globalThis?globalThis:e||self).askForPromise=n()}(this,function(){"use strict";function e(e){return e?function(e){let i=e.map(e=>n()),u=i.map(e=>e.promise);i.promises=i;let r=o(Promise.all(u));function c(e){let n="pending";return e.then(()=>n="fulfilled").catch(()=>n="rejected"),n}function l(n,...o){i.forEach((t,i)=>n({value:e[i],done:t.done,cancel:t.cancel,timeout:t.timeout,state:c(t.promise)},...o))}const s={promise:Promise.all(u),promises:i,done:e=>{i.forEach(n=>n.done(e))},cancel:e=>{i.forEach(n=>n.cancel(e))},each:l,onComplete:r,timeout:()=>{}};return s.timeout=t(!0,s),s}(e):n()}function n(){let e,n;const i=new Promise((o,t)=>{e=o,n=t}),u={promise:i,promises:null,done:e,cancel:n,each:()=>{},onComplete:o(i),timeout:()=>{}};return u.timeout=t(!1,u),u.each=(o,...t)=>{o({value:null,done:e,cancel:n,timeout:u.timeout},...t)},u}function o(e){return function(n,o=null){null===o?e.then(e=>n(e)):e.then(e=>n(e),e=>o(e))}}function t(e,n){let t;return t=e?Promise.all(n.promises.map(e=>e.promise)):n.promise,function(e,i){let u,r=new Promise((n,o)=>{u=setTimeout(()=>{n(i),Promise.resolve(t)},e)});return t.then(()=>clearTimeout(u)),n.onComplete=o(Promise.race([t,r])),n}}return e.sequence=function(n,...o){const t=e(),i=[];const u=function*(e){for(const n of e)yield n}(n);return function e(n,...o){n.done?t.done(i):n.value(...o).then(n=>{i.push(n),e(u.next(),...o,n)})}(u.next(),...o),t},e.all=function(n,...o){const t=e(),i=[],u=n.map((e,n)=>"function"==typeof e?e(...o).then(e=>i[n]=e):e.then(e=>i[n]=e));return Promise.all(u).then(()=>t.done(i)),t},e});