Promise.all 批量獲取數據

Promise.all 批量獲取數據 :

    const hdcms = new Promise((resolve, reject) => {
        setTimeout(() => {
            // resolve('第一個異步');
            reject('第一個異步錯誤。。。')
        }, 1000);
    }).catch(error => {
        console.log(3333333333);
    })

    const zhongguo = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('第二個異步');
        }, 1000);
    });

    Promise.all([hdcms, zhongguo]).then(result => {
        console.log('1111111', result);
    }).catch(error => {
        console.log('222222', error);
    })
    // 3333333333
    // 1111111 (2) [undefined, "第二個異步"]
    

Promise.all 封裝 批量獲取數據

    function getUser(names) {
        let promises = names.map(name => {
           	// return  ajax(`http://localhost:8888/php/user.php?name=${name}`)
            return {
                // ajax  請求得到數據
                status: 200,
                data: {
                    age: 10,
                    age: 11
                }
            }
        });
        return Promise.all(promises)
    }

    getUser(['中國', '湖北']).then(users => {
            console.log(users);
        })
        // (2) [{…}, {…}]
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章