ES6 入门教程
仓库源码:https://github.com/bosombaby/javascript
const promise = new Promise((resolve, reject) => {
resolve(1)
})
const p1 = promise
.then((num) => {
console.log('第一层 then', num)
return num + 1
})
.then((num) => {
console.log('第二层 then', num)
return num + 1
})
.then((num) => {
console.log('第三层 then', num)
throw Error('出错')
})
.catch((err) => {
console.log('捕获错误', err)
})
console.log(p1)
const test1 = async () => {
return 1
}
const promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve('success')
}, 1500)
})
async function test() {
console.log('before')
const data = await promise
console.log('data', data)
console.log('after')
}
//上面代码等价于
async function test1() {
console.log('before')
promise.then((data) => {
console.log('data', data)
console.log('after')
})
}
test1()
// 三、try catch对应Promise.catch
async function test() {
const promise = Promise.reject('出错') //2
try {
console.log('before') //1
const data = await promise
console.log('data', data)
} catch (e) {
console.error(e) //3
}
}
从一道让我失眠的 Promise 面试题开始,深入分析 Promise 实现细节 - 掘金
Promise.MyAll = function (promises) {
let result = []
return new Promise((resolve, reject) => {
promises.forEach((item, index) => {
Promise.resolve(item)
.then((res) => {
result[index] = res
if (Object.keys(result).length === promises.length) resolve(result)
})
.catch((err) => {
reject(err)
})
})
})
}
Promise.myRace = function (promises) {
return new Promise((resolve, reject) => {
for (let item of promises) {
Promise.resolve(item).then(resolve, reject)
}
})
}
Promise.myAny = function (promises) {
let result = []
return new Promise((resolve, reject) => {
promises.forEach((item, index) => {
Promise.reject(item).then(resolve, (err) => {
result[index] = { status: 'rejected', msg: err }
if (Object.keys(result).length === promises.length) reject(result)
})
})
})
}
Promise.myAllSettled = function (promises) {
let result = []
return new Promise((resolve, reject) => {
const processResult = (index, msg, status) => {
result[index] = { status, msg }
if (Object.keys(result).length === promises.length) resolve(result)
}
promises.forEach((item, index) => {
Promise.resolve(item)
.then((res) => {
processResult(index, res, 'fulfilled')
})
.catch((err) => {
processResult(index, err, 'rejected')
})
})
})
}