Last active
July 22, 2018 11:06
-
-
Save keicoon/44fea17da90332c355773ee7c1ed20a6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//####################################### | |
// Selector Promise | |
class Selector extends Task { | |
run() { | |
let index = 0, length = this.children.length | |
return new Promise((resolve, reject) => { | |
const tick = () => { | |
this.children[index].run().then( | |
() => { | |
resolve() | |
}, | |
() => { | |
if (++index >= length) | |
reject() | |
else | |
this.nextTick(tick) | |
} | |
) | |
} | |
this.nextTick(tick) | |
}) | |
} | |
} | |
// Selector async await | |
class Selector extends Task { | |
async Run() { | |
// | |
for(const child of this.children) { | |
const result = await child.Run() | |
// break point | |
if(result) return result | |
} | |
// | |
return false | |
} | |
} | |
//####################################### | |
// parallel promise | |
class Parallel extends Task { | |
run() { | |
return new Promise((resolve, reject) => { | |
this.children.forEach(child => { | |
this.runningChildren.push(child) | |
child.run().then( | |
() => { | |
this.runningChildren.splice(this.runningChildren.indexOf(child), 1) | |
if (this.runningChildren.length <= 0) | |
resolve() | |
}, | |
() => { | |
this.terminate() | |
reject() | |
} | |
) | |
}) | |
}) | |
} | |
} | |
// parallel async await | |
class Parallel extends Task { | |
Run() { | |
return new Promise((resolve, reject) => { | |
let waitingChildrenLength = this.children.length | |
_.each(this.children, child => child.Run().then(result => { | |
if(result == false) resolve(false) | |
else if(--waitingChildrenLength < 1) resolve(true) | |
})) | |
}) | |
} | |
} | |
//####################################### | |
// funcA, funcB is not Promise Function! | |
// promise chain | |
awesomePromsie() | |
.then(__ => funcA()) | |
.then(rv_funcA => funcB(rv_funcA)) | |
.then(rv_funcB => promiseFuncA(rv_funcB)) | |
.then(result => console.log(result)) | |
.catch(reject => console.error(reject)) | |
// awesome async & await | |
const rv_funcA = funcA() | |
const rv_funcB = funcB(rv_funcA) | |
try{ | |
const result = await promiseFuncA(rv_funcB) | |
console.log(result) | |
} catch(reject) { | |
console.error(reject) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment