javascript - fetch 可以同步请求数据吗?
PHPz
PHPz 2017-04-11 11:13:55
0
3
1417

fetch(userLoginUrl, {

            method: 'POST',
            headers: {
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify(userObj),
        }).then(function (res) {
            if (res.ok) {
                res.json().then(function (data) {
                    //console.log(data);
                    if (data.code == 0) {
                        dataTest = data;
                        dataBu = true;
                        applyFn(data);
                        //上面成功后再次出一个请求 ????
                    }

                });
            }
        }).catch(function (err) {
            // console.log(err)
        });
        
PHPz
PHPz

学习是最好的投资!

reply all(3)
阿神
fetch(userLoginUrl, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json;charset=UTF-8'
    },
    body: JSON.stringify(userObj),
}).then(function (res) {
    if (res.ok) {
        // return
        return res.json().then(function (data) {
            //console.log(data);
            if (data.code == 0) {
                dataTest = data;
                dataBu = true;
                applyFn(data);
                return fetch(url) // 第二个请求
            }

        });
    }
}).then(function(res){
console.log('第二请求')
}).catch(function (err) {
    // console.log(err)
});
小葫芦

fetch同步请求似乎好像没有,虽然文档中有提到一个synchronous-flag,但是调用参数里面没有提供这个配置项。
不是很明白你需要做什么。如果你是要在userLoginUrl的请求成功后再发送另外一个请求,那么你注释的地方再调用个请求就行了。本来在then就是在请求成功后才会调用的。

刘奇

ES7的话,可以用async/await用同步的思维写异步的代码。

async function fn() {
    let res_1 = fetch(url_1);
    let res_2 = fetch(url_2, res_1);
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!