🐣
Javascript - How promises work?
作成日:
2021/05/18
2
Javascript Promises
Promises are special objects that can continue operations in asynchronous mode. They use a resolve
and reject
callbacks to finalize tasks.
Syntaxis
const myTask = new Promise((resolve, reject) => {
// TODO: Do some complex operation, when you finish resolve the task
// Example: Download some file and resolve with the result or the error
download(url, (error, result) => {
if (error) {
reject(error) // Resolve with error
return
}
resolve(result) // Resolve without error
})
})
Call the promise and handle the flow
When the promise is resolved you can continue operation flow into a then
callback or handle the error into the catch
callback.
myTask.then(result => {
// TODO: Continue with the result passing into `resolve` callback
console.log(`Success with result`, result)
}).catch(error => {
// TODO: Handle the error to avoid crashing.
console.error(`This is the error generated: ${error}`)
// TODO: Continue here (when error was generated)
})
Create a Promise chain
downloadFile(url).then(file => {
return saveFile(file)
}).then(result => {
return notifyFileSaved(result)
}).catch(error => {
console.log(`There was an error in some place of the chain. Error is ${error}`)
})
Create your own functions returning promises
You can make functions that return promises.
function waitFor(time) {
return new Promise(resolve => setTimeout(resolve, time))
}
console.log("Waiting for 10s...")
waitFor(10000).then(() => {
console.log("Now 10s have passed")
// TODO: Continue operations
})
Algorithms and mathematics merge with artificial intelligence in a heightened zen state, to make way for the dragon.