SOURCE

// 封装方法
function GetUserInfoAsync(aa) {
    return new Promise((resolve, reject) => {
        if (aa == 1) {
            setTimeout(() => {
                resolve('1111111');
            }, 2000);
        }
        else if (aa == 2) {
            resolve('2222222');
        } else {
            reject('3333333');
        }
    })
};

// async/await 语法,可以更像同步代码地处理异步逻辑
async function OnLoad() {
    try { 
        var a = await GetUserInfoAsync(1);
        var b = await GetUserInfoAsync(2);
        console.log(a, b);
        console.log('多个结束');
    }
    catch (error) {
        console.error('多个出错:', error)
    }
};
// 并行处理多个异步  接收一个 Promise 数组,只有当所有 Promise 都成功时才返回成功结果,否则立即以第一个失败的原因拒绝
function PromiseAll() {
    const promise1 = GetUserInfoAsync(1).then(res => res);
    const promise2 = GetUserInfoAsync().then(res => res);
    
    Promise.all([promise1, promise2])
        .then(results => console.log('所有数据:', results))
        .catch(error => console.error('其中一个失败:', error));
    
};

// 单个使用
function Single() {
    GetUserInfoAsync()
        .then(res => console.log(res))    // 输出: "数据获取成功!"
        .catch(error => console.error(error))   // 输出: "数据获取失败!"
        .finally(() => console.log("单个操作完成"));
};


OnLoad();

PromiseAll();

Single();
console 命令行工具 X clear

                    
>
console