Promise Object in Javascript
1. Concurrency models#
- Processes
- Threads (system or green)
- Futures
- Asynchronous operations, non-blocking, single-threaded
- Coroutines
- CSP
- Actor
Learn more: java - What’s the difference between a Future and a Promise? - Stack Overflow
2. Promise object#
- A wrapper for a resolved value or a reason that it’s not resolved yet.
- But with some powerful methods, allow you handle different situations.
- Like the
then
chain, thecatch
- Non-blocking: enable you to write asynchronous code in a synchronous manner.
- Most important feature.
- There are more complicated methods,
The Promise
object has several fields and methods, including:
state
: A private field that represents the current state of the promise (pending
,fulfilled
orrejected
).result
: A private field that holds the result value if the promise is fulfilled or the reason if it is rejected.then()
,catch()
,finally()
methods, only get executed when the state of Promise object isfulfilled
orrejected
.
3. Use await/async
with Promise object#
async function main() {
let response
try {
// 'response' is not a Promise object,
// it's the resolved value the in the Promise object
response = await fetch('https://www.google.com');
} catch (err) {
console.error("an err happened");
return
}
console.log(response.ok);
}
main().then()
You may wonder why we need call then()
after main()
, the reason is that async functions
always return a promise implicitly.
If the return value of an
async
function is not explicitly a promise, it will be implicitly wrapped in a promise. Anasync
function is really just a fancy Promise wrapper.
If you call main like this:
...
await main();
There will be an error:
await main();
^^^^^
SyntaxError: await is only valid in async functions and the top level bodies of modules
This is another syntax to call async function:
(async () => {
await main()
})()
查看其他文章