失效链接处理 |
The Complete JavaScript Handbook PDF 下载
本站整理下载:
提取码:i0bd
相关截图:
主要内容:
Promises Promises allow us to eliminate the famous “callback hell”, although they introduce a bit more complexity (which has been solved in ES2017 with async , a higher level construct). Promises have been used by JavaScript developers well before ES2015, with many diierent library implementations (for example, jQuery, q, deferred.js, vow…). The standard created a common ground across the diierences. By using promises, you can rewrite this code
setTimeout(function() {
console.log('I promised to run after 1s')
setTimeout(function() {
console.log('I promised to run after 2s')
}, 1000)
}, 1000)
as
const wait = () => new Promise((resolve, reject) => {
setTimeout(resolve, 1000)
})
wait().then(() => {
console.log('I promised to run after 1s')
return wait()
})
.then(() => console.log('I promised to run after 2s'))
Generators Generators are a special kind of function with the ability to pause themselves, and resume later, allowing other code to run in the meantime. The code decides that it has to wait, so it lets other code “in the queue” run, and keeps the right to resume its operations “when the thing it’s waiting for” is done. All this is done with a single, simple keyword: yield . When a generator contains that keyword, the execution is halted.
A generator can contain many yield keywords, thus halting itself multiple times, and it's identibed by the *function keyword, which is not to be confused with the pointer dereference operator used in lower level programming languages such as C, C++ or Go. Generators enable whole new paradigms of programming in JavaScript, allowing: • 2-way communication while a generator is running • long-lived while loops which do not freeze your program Here is an example of a generator which explains how it all works.
function *calculator(input) {
var doubleThat = 2 * (yield (input / 2))
var another = yield (doubleThat)
return (input * doubleThat * another)
} We initialize it with
const calc = calculator(10)
Then we start the iterator on our generator:
calc.next()
This brst iteration starts the iterator. The code returns this object: {
done: false
value: 5
}
What happens is: the code runs the function, with input = 10 as it was passed in the generator constructor. It runs until it reaches the yield , and returns the content of yield : input / 2 = 5 . So we get a value of 5, and the indication that the iteration is not done (the function is just paused). In the second iteration we pass the value 7 :
calc.next(7)
and what we get back is: {
done: false
value: 14
}
|