当前位置: 首页 > 工具软件 > node-promise > 使用案例 >

NodeJS 05_Promise

暨承平
2023-12-01

Promise的静态方法

Promise.resolve() 创建一个立即完成的Promise

Promise.resolve(10).then(r => { console.log(r); })

Promise.reject() 创建一个立刻拒绝的Promise

Promise.reject("错误").catch(r =>{console.log(r);})

Promise.all([...]) 同时返回多个Promise的执行结果

 注:若有一个报错,则返回错误

function sum(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a + b)
        }, 1000)
    })
}

Promise.all([
    sum(123, 456),
    sum(5, 6),
    // Promise.reject("哈哈"),
    sum(33, 44)
]).then(r =>{
    console.log(r);
})

运行结果:

(3) [579, 11, 77]


Promise.allSettled([...]) 同时返回多个Promise的执行结果(无论成功或失败)

function sum(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a + b)
        }, 1000)
    })
}

Promise.allSettled([
    sum(123, 456),
    sum(5, 6),
    Promise.reject("哈哈"),
    sum(33, 44)
]).then(r => {
    console.log(r);
})

运行结果:

(4) [{…}, {…}, {…}, {…}]

0:{status: 'fulfilled', value: 579}

1:{status: 'fulfilled', value: 11}

2:{status: 'rejected', reason: '哈哈'}

3:{status: 'fulfilled', value: 77}


Promise.race([...]) 返回执行最快的Promise,不考虑对错

function sum(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a + b)
        }, 1000)
    })
}

Promise.race([
    Promise.reject(1111),
    sum(123, 456),
    sum(5, 6),
    sum(33, 44)
]).then(r => {
    console.log(r);
}).catch(r =>{
    console.log("错误");
})

Promise.any([...]) 返回执行最快的正确的Promise

function sum(a, b) {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve(a + b)
        }, 1000)
    })
}

Promise.any([
    Promise.reject(1111),
    Promise.reject(1111),
    Promise.reject(1111),
]).then(r => {
    console.log(r);
}).catch(r =>{
    console.log("错误",r);
})

 类似资料:

相关阅读

相关文章

相关问答