-
Notifications
You must be signed in to change notification settings - Fork 4
Migrating from Promises
Yannick Spark ⚡️ edited this page May 10, 2017
·
1 revision
let myPromise = new Promise(function(resolve, reject) {
setTimeout(resolve, 300)
})
myPromise
.then(_ => "Timeout done !")
.then(value => {
throw "oops!"
})
.then(_ => "There was an error up there. I won't be received.")
.catch(error => console.log(`Caught the error : ${error}`))
.then(_ => "Everything's fine now !")
// `Task` is the constructor
let myTask = Task(function(reject, resolve) { // arguments are flipped
setTimeout(resolve, 300)
})
// It has the same semantics with `.then` and `.catch`
myTask
.then(_ => "Timeout done !")
.then(value => {
throw "oops!"
})
.then(_ => "There was an error up there. I won't be received.")
.catch(error => console.log(`Caught the error : ${error}`))
.then(_ => "Everything's fine now !")
// BUT ... the computation is deferred.
// It must be run using `.fork(errorCb, successCb)` or `.run(successCb)`.
let myRunningTask = myTask.fork(
// No more `Unhandled rejection` errors. You're forced to handle error at the end of the chain.
(error) => console.log(`Got the error : ${error}`),
(finalResult) => console.log(`The final result is : ${finalResult}`)
)
// OR
// `.run(cb)` is an alias for `.fork(console.error, cb)`
let myRunningTask = myTask.run(finalResult => console.log(`The final result is : ${finalResult}`))
BONUS
You may want to cancel the computation :
let myTask = Task(function(reject, resolve) { // arguments are flipped
let timeoutHandler = setTimeout(resolve, 300)
// If you want it to be cancellable
let cancelTimeout = () => clearTimeout(timeoutHandler)
return { cancel: cancelTimeout }
})
/* ... */
// Let's cancel it !
myRunningTask.cancel()