Reference: https://es6.ruanyifeng.com/#docs/promise
Common functions
Promise.prototype.then()
Promise.prototype.catch()
Promise.prototype.finally()
Promise.all()
Promise.race() //率先改变状态,p的状态就跟着改变
Promise.allSettled()
Promise.any()
Promise.resolve()
Promise.reject()
Promise.try()
Table of contents
what is promise?
Promise
, which is simply a container that holds the result of an event (usually an asynchronous operation) that will end in the future. Syntactically, Promise
an object from which messages for asynchronous operations can be obtained. Promise
Provide a unified API, and various asynchronous operations can be processed in the same way. Simply put, the role of promise is 将异步操作以同步操作的流程表达出来
to avoid nested callback functions.
Features of promises
- A promise asynchronous operation has three states:
进行中,已成功,已失败
. Only asynchronous operations can change this state. - Once the promise state changes, it will not change again. There are two possibilities for the change of the promise object,
进行中—>已成功,进行中—>已失败
.
Basic usage of promises
A promise object is a 构造函数
promise instance that is used to generate:
const promise = new Promise(function(resolve, reject) {
// ...
if (/* 满足条件 成功 反之失败 */){
resolve(value);
} else {
reject(error);
}
});
Example:
promise1(){
new Promise(function(resolve, reject) {
let intData = Math.floor (Math.random()*10)
if (intData > 3){
resolve('数据正确,大于3');
} else {
reject('数据错误,小于3');
}
}).then(res=>{
console.log(res)
}).catch(e=>{
console.log(e)
})
}
The accepted parameters are resolve
and reject
two functions:
resolve的作用
: the state of the promise object by 进行中—>已完成
. And pass the result of the asynchronous operation as a parameter
rejected的作用
: pass the state of the promise object by 进行中—>已失败
and the reason for the asynchronous failure as a parameter.
Usage of then
The then method can accept two callback functions as parameters. The first callback function is called when the state of the promise object is resolve (completed), and the second callback function (optional) is called when the state of the promise object is reject (failed). ) when called.
function timeout(ms) {
return new Promise((resolve, reject) => {
setTimeout(resolve, ms, 'done');
});
}
timeout(100).then((value) => {
console.log(value);
});
Chained then usage
The then method returns a new Promise instance (note, not the original Promise instance). Therefore, the chain writing method can be used, that is, another then method is called after the then method.
getJSON("/post/1.json").then(function(post) {
return getJSON(post.commentURL);
}).then(function funcA(comments) {
// 成功
console.log("resolved: ", comments);
}, function funcB(err){
// 错误
console.log("rejected: ", err);
});
In the above code, the callback function specified by the first then method returns another Promise object. At this time, the callback function specified by the second then method will wait for the state of the new Promise object to change. If it becomes resolved, funcA is called, and if the state becomes rejected, funcB is called.
catch method
In the promise object, if the asynchronous operation throws an error, the status will become rejected, and the callback function specified by the catch method will be called to handle the error. In addition, the callback function specified by the then method will also be caught if an error is thrown during operation. method capture.
p.then((val) => console.log('fulfilled:', val))
.catch((err) => console.log('rejected', err));
// 等同于
// 等同于
p.then((val) => console.log('fulfilled:', val))
.then(null, (err) => console.log("rejected:", err));
The error of the promise object has a "bubbling" nature and will be passed backward until it is caught, that is, it will skip the then function in the middle
getJSON('/post/1.json').then(function(post) {
return getJSON(post.commentURL);
}).then(function(comments) {
// some code
}).catch(function(error) {
// 处理前面三个Promise产生的错误
});
finally method
The finally method is used to specify an action that will be performed regardless of the final state of the promise object.
server.listen(port).then(function () {
// ...
}).finally(server.stop);
The server handles the request with a promise and then shuts down the server with the finally() method.
promise.all() method
The promise.all method is used to wrap multiple promise instances into a new promise instance.
const p = Promise.all([p1, p2, p3]);
The Promise.all method accepts an array as a parameter, the elements of which are all promise instances, 如果不是,则会自动将参数转变为promie实例
.
The state of p is determined by the elements in its array, which are divided into two states (using the above example)
Only when the state of p1 p2 p3 becomes fulfilled (completed) will it become fulfilled (completed). At this time, the return values of p1 p2 p3 form an array and pass it to the callback function of p.
Among p1 p2 p3, one is rejected (unfinished), and the status of p will become rejected (unfinished). At this time, the return value of the first rejected instance will be passed to the callback function of p.
promise.race() method
The Promise.race method also wraps multiple Promise instances into a new Promise instance
const p = Promise.race([p1, p2, p3]);
一个实例率先改变
There are states among p1, p2, and p3 , p的状态就跟着改变
. The return value of the Promise instance that changed first is passed to p's callback function.
async function
Notice:! ! The await command can only be used in async functions, and an error will be reported in ordinary functions.
The introduction of async makes asynchronous operations more convenient. What is the async function, in fact, it is the syntactic sugar of the Generator function. Make asynchronous functions and callback functions look more like synchronous functions in syntax. Generator is not introduced here. Let's go straight to learning async
The return value of async is a promise object, so you can use the then method to add a callback function. When the function is executed, once it encounters await, it will return first, wait until the asynchronous operation is completed, and then execute the content behind the function body.
async function getStockPriceByName(name) {
const symbol = await getStockSymbol(name);
const stockPrice = await getStockPrice(symbol);
return stockPrice;
}
getStockPriceByName('goog').then(function (result) {
console.log(result);
});
The use form of async function
//函数声明
async function foo(){
}
//函数表达式
const foo = async function(){
};
//对象的方法
let obj = {
async foo(){
}};
obj.foo().then(...)
//箭头函数
const foo =async()=>{
};
The value returned by the return statement inside the async function will become the parameter of the then method calling function.
async function f(){
return ‘hello world’;
}
f().then(v=> console.log(v))
//"hello world"
await command
Under normal circumstances, the await command is followed by a promise object, if not, it will be automatically converted to a promise object
async function f(){
return await 123;
}
f().then(v =>console.log(v))
//123
!! When the promise after an await statement becomes reject, the entire function will be interrupted.
async function f() {
await Promise.reject('出错了');
await Promise.resolve('hello world'); // 不会执行
}
error handling
If the asynchronous operation behind await is wrong, then the promise object equivalent to that returned by the async function will be rejected (as mentioned above when talking about the promise object, bubbling nature)
async function f() {
await new Promise(function (resolve, reject) {
throw new Error('出错了');
});
}
f().then(v => console.log(v))
.catch(e => console.log(e))
// Error:出错了
Use try...catch blocks to prevent errors.
async function f() {
try {
await new Promise(function (resolve, reject) {
throw new Error('出错了');
});
} catch(e) {
}
return await('hello world');
}
Multiple await commands are placed in try...catch structures
async function main() {
try {
const val1 = await firstStep();
const val2 = await secondStep(val1);
const val3 = await thirdStep(val1, val2);
console.log('Final: ', val3);
}
catch (err) {
console.error(err);
}
}
Related properties
The difference between allSettled() and all()
- all() returns a direct wrapper
resolve内容的数组
, allSettled() returns a wrapper对象的数组
. - all() If a Promise object reports an error, all() cannot be executed, your error will be reported, and other successful data cannot be obtained. The allSettled() method returns all the data of the Promise instance into an object regardless of whether there is an error. If it is resolved data, the status value is fulfilled, otherwise it is rejected.
Promise.resolve() 与 Promise.reject()
resolve 成功
reject 失败
Promise.try()
Troubleshoot.