Promise
Promise can be pending, resolved or rejected
The disadvantages of a Promise object are:
-
You cannot cancel a Promise, it is executed as soon as it is created, and you cannot cancel it in mid-stream.
-
If the callback function is not set, the errors thrown by the Promise internally are not reflected externally.
-
When you are in the Pending state, you have no way of knowing where you are (just started or about to finish).
-
By the time a Promise actually executes the callback, the part that defines a Promise is actually gone, so the error stack context for a Promise is not very friendly.
Generator
A Generator is a new syntax introduced in ES6. A Generator is a function that can pause and continue execution.
A simple way to use it is to use it as an Iterator, doing some iterating. For more complex uses, it can store some states internally, making it a state machine.
The Generator’s basic syntax consists of two parts: the function name is preceded by an asterisk; The function returns the value internally using the yield keyword.
-
Yield, the expression itself returns no value, or always returns undefined.
-
Next, the method can take an argument, which is treated as the return value of the previous yield expression.
function * foo(x) {
var y = 2 * (yield (x + 1));
var z = yield (y / 3);
return (x + y + z);
}
var b = foo(5);
b.next() // { value:6, done:false }
b.next(12) // { value:8, done:false }
b.next(13) // { value:42, done:true }
Copy the code
Async(recommended ~ ~)
Async is a syntax sugar for Generator.
Async corresponds to *.
Await corresponds to yield.
Async /await automates the flow control of the Generator.
async function fetchUser() {
const user = await ajax()
console.log(user)
}
Copy the code
- Note: If the current function needs to be executed asynchronously, use async again. Cause: Babel recognizes and compiles async to promise, resulting in an increase in code.
Why is Async/Await better?
-
Using async makes your code much cleaner. You don’t need to write a then like a Promise, you don’t need to write an anonymous function to handle the Promise’s resolve value, you don’t need to define redundant data variables, and you avoid nesting code.
-
Error handling: Async/Await lets try/catch handle both synchronous and asynchronous errors.