鍍金池/ 問答/HTML/ 待兩個接口都返回再操作的情況,怎么處理,有哪些解決方法

待兩個接口都返回再操作的情況,怎么處理,有哪些解決方法

fetch('http://10.3.134.173/jsonp-test/data/dish_getbypage.php?start=1',
    ).then((response)=>
        response.json()
    ).then((res)=>{
        console.log(res[0].name);
    });
fetch('http://10.3.134.173/jsonp-test/data/dish_getbypage.php?start=2',
    ).then((response)=>
        response.json()
    ).then((res)=>{
        console.log(res[0].name);
    })

同時發(fā)起請求,比如一個等待一秒,一個等待兩秒返回,然后待都返回結(jié)果然后執(zhí)行后續(xù)操作,具體該怎么操作,用promise.all怎么寫

回答
編輯回答
誮惜顏
提問前,代碼請勿使用圖片

假設(shè)你的兩個promise分別是 Func1()Func2()

let pr_task = [Func1,Func2];
Promise.all(pr_task).then(function(){
    //Here,code  After All Promise
})

根據(jù)問題的補充

fetch('http://10.3.134.173/jsonp-test/data/dish_getbypage.php?start=1',
    ).then((response)=>
        response.json()
    ).then((res)=>{
        console.log(res[0].name);
    });
fetch('http://10.3.134.173/jsonp-test/data/dish_getbypage.php?start=2',
    ).then((response)=>
        response.json()
    ).then((res)=>{
        console.log(res[0].name);
    })

如果你是想等 fetch('http://10.3.134.173/jsonp-test/data/dish_getbypage.php?start=1'),那么直接

let pr_task = [];
pr_task.push(fetch('http://10.3.134.173/jsonp-test/data/dish_getbypage.php?start=1'))
pr_task.push(fetch('http://10.3.134.173/jsonp-test/data/dish_getbypage.php?start=2'))

Promise.all(pr_task).then(function(){
    //Here,code  After All Promise
})

只要保證pr_task這個數(shù)組的值都是一個promise,那么Promise.all()就會等待所有的數(shù)據(jù),并且按照原數(shù)組的順序給出resolve的結(jié)果組成的一個數(shù)組

2017年10月17日 06:04
編輯回答
維她命

Promise.all

2017年4月20日 19:14
編輯回答
浪婳

你的需求應(yīng)該是 第一個接口數(shù)據(jù)拿到之后 再拿第二個接口的數(shù)據(jù)?

2017年2月22日 11:29
編輯回答
有你在

首先我的是基于axios的 也就是封裝的promise

        getUser () { 
            return this.$http.get('/api/v1/account/login_user')
        },
        getUserFeedback () {
            return this.$http.get('/api/v1/user_feedbacks')
        }
        接下來就是等待回調(diào)
        this.$http.all([this.getUser(),this.getUserFeedback()])
            .then(this.$http.spread(function(acct,perms){
                acct和perms也就是你兩個后端接口返回的data,也就你可以操作數(shù)據(jù)
        }))
        希望幫到你
2017年5月3日 05:10
編輯回答
怪痞
let p1 = new Promise((resolve, reject) => {
    // 第一個接口請求
    fetch('....').then((res) => {
        resolve(res);
    })
})

let p2 = new Promise((resolve, reject) => {
    // 第二個接口請求
    fetch('....').then((res) => {
        resolve(res);
    })
})

Promise.all([p1,p2]).then(data => {
    console.log(data);
})
2018年2月2日 03:17