Last active
December 10, 2017 15:26
-
-
Save ashl1/9b1150e23a9fef2e36a81c8d944995d8 to your computer and use it in GitHub Desktop.
Promise chain graph
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
(({timeout1, timeout2}) => { | |
const startOp = (name, timeout) => () => { | |
console.log(name + ' started at ' + Date.now()) | |
return new Promise(function(resolve) { | |
setTimeout(function() { | |
resolve(); | |
}, timeout); | |
}); | |
} | |
const start = Date.now(); | |
const op1 = startOp('StartOp1', timeout1)(); | |
const op2 = startOp('StartOp2', timeout2)(); | |
op1.then(function() { | |
// Fires when op1 is successful; doesn't care about op2 | |
console.log("op1 done after " + (Date.now() - start) + "ms"); | |
}); | |
op2.then(function() { | |
// Fires when op2 is successful; doesn't care about op1 | |
console.log("op2 done after " + (Date.now() - start) + "ms"); | |
}); | |
Promise.all([op1, op2]).then(function() { | |
// Fires when BOTH ops are successful | |
console.log("both done after " + (Date.now() - start) + "ms"); | |
}); | |
})({ | |
timeout1: 1000, | |
timeout2: 2000 | |
}) | |
// We can has as many points to branch as want. Thus we can make a graph of executions | |
(({timeout1, timeout2}) => { | |
const startOp = (name, timeout) => async () => { | |
console.log(name + ' started at ' + Date.now()) | |
return new Promise(function(resolve) { | |
setTimeout(function() { | |
resolve(); | |
}, timeout); | |
}); | |
} | |
const start = Date.now(); | |
const op1 = startOp('StartOp1', timeout1)(); | |
const op2 = op1.then(() => startOp('StartOp2', timeout2)()); | |
Promise.all([op1, op2]).then(function() { | |
// Fires when BOTH ops are successful | |
console.log(Date.now() + " both done after " + (Date.now() - start) + "ms"); | |
}); | |
op1.then(function() { | |
// Fires when op1 is successful; doesn't care about op2 | |
console.log(Date.now() + " op1 done after " + (Date.now() - start) + "ms"); | |
}); | |
op2.then(function() { | |
// Fires when op2 is successful; doesn't care about op1 | |
console.log(Date.now() + " op2 done after " + (Date.now() - start) + "ms"); | |
}); | |
})({ | |
timeout1: 1000, | |
timeout2: 2000 | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Если у тебя есть цепочка асинхронных операций - намного удобнее использовать async/await:
С continuation-цепочками это выглядело бы так: