The relationship between async / await and Promise
async/await is the syntactic sugar of Promise,
so here I will directly use async/await to replace Promise
let result = await func()
// => 等价于
func().then(result => {
// code here
})
// ======
async function func () {
return 1
}
// => 等价与
function func () {
return new Promise(resolve => resolve(1))
}
map
map can be said to be the most friendly function to Promise.
We all know that map receives two parameters:
1. The callback executed for each element, the return value of the callback result will be used as the corresponding subscript element in the array
2. An optional parameter pointed to by this of the callback function
There will be such a scene in daily work.
This is the general usage scene of map, but when some of our calculation operations become asynchronous: for example, a certain parameter needs to request an additional interface to get it. At this
time, the returned array is composed of Promise.
So why do you say that the map function is the most friendly, and Promise has a function that isPromise.allRight, it will execute the array composed of Promise in sequence and return a Promise object, then the result set will come out.
Wrap the entire array with Promise.all, then await to get the final result, and
finally attach the code:
let list = [];
let array = [{
path: "1" }, {
path: "2" }, {
path: "3" }];
list = await Promise.all(
array.map(async (item) => {
return {
...item,
y_path: await this.getImage(item.path)
};
})
);
Original link:
https://www.cnblogs.com/mica/p/15577084.html
Let's study together, come on!