Promise and async/await both handle asynchronous requests
Make a promise
There are three state-chain calls to promise
Error trapping
Async and await
usage
Error trapping
The problem with synchronous and asynchronous JS is usually referred to as ajax callbacks. If it is a synchronous call, the application will pause after making an Ajax call and will not resume running until the remote server responds. In an asynchronous call, the program does not pause after making an Ajax call, but executes the following code immediately, and the server returns information that triggers the callback function for processing. Asynchronous calls, by contrast, have the best performance, with no program stalling, while synchronous calls are typically used for situations where results need to be obtained immediately and processed in real time.
The use of the promise
A Promise, simply, is a container that holds some future end time (usually the result of an asynchronous operation)
Basic syntax:
let p = new Promise((resolve,reject) => {
//...
resolve('success')
});
p.then(result => {
console.log(result);//success
});
Copy the code
Promise has three states
A pending B failure C failure D failure
Chain calls
Error trapping
Promise.prototype. Catch specifies the.then callback when the Promise state is rejected, and returns the same value as.then
`let p = new Promise((resolve,reject) => {
reject('error'); }); p.catch(result => { console.log(result); }) `Copy the code
Async and await
Brevity: The ultimate in asynchronous programming is not caring whether it is asynchronous or not. Async and await solve this problem by forcing asynchrony into synchronous processing. There is no substitution of async/await and promise because async/await is a syntactic sugar parasitic on promise, Generater.
usage
Async is used to declare that a function is asynchronous, and await can be thought of as short for async wait, to wait for an asynchronous method to complete. Rule: 1 Async and await are used in pairs, and await is inside async. ‘2 await’ means to wait for a promise to return, and then ‘3 await’ should be followed by a Promise object.
Async function demo() {let result01 = await sleep(100); // let result02 = await sleep(result01 + 100); let result03 = await sleep(result02 + 100); // console.log(result03); return result03; }
demo().then(result => { console.log(result); }); `Copy the code
Error trapping
If it is reject, you can use a try-catch
let p = new Promise((resolve,reject) => {
setTimeout(() => {
reject('error'); }, 1000); }); asyncfunction demo(params) {
try {
let result = await p;
}catch(e) {
console.log(e);
}
}
demo();
Copy the code
The difference between:
1 promise is ES6, async/await is ES7 2 Async /await is more elegant than promise 2) async/await can be used. Then try-catch can be usedCopy the code