如何在fetch then / response函数中访问请求对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在fetch then / response函数中访问请求对象相关的知识,希望对你有一定的参考价值。

我有一个遍历数组的javascript循环。对于每个项目,我执行获取请求以插入对象。如果服务器响应指示它是已插入的对象,我尝试使用另一个提取调用进行更新操作。

由于请求是异步的,循环在我尝试更新操作之前将请求对象设置为下一个插入项,因此我最终请求更新尚未插入的对象。

有没有办法可以访问用于此获取操作的请求对象,所以我可以使用该对象而不是循环var?

我在promise方法中尝试使用this,但它返回对window对象的引用:console.log(this) ==> > Window http://localhost

我的代码:

for (var i = 0; i < expectedRows; i++) {
    var row = myArray[i];
    customerCode = row['customer_code'];
    customerName = row['customer_name'];
    customerBalance = row['customer_balance'];
    // Build body call
    var callBody = {
        user: 'USER',
        code: customerCode,
        name: customerName,
        balance: customerBalance
    };
    var fetchOptions = {
        method: "POST",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "error",
        referrer: "ux-import", 
        body: JSON.stringify(callBody),
    };
    // Call
    var epurl = baseEP + '/customer/create';
    fetch(epurl, fetchOptions)
    .then(response => response.json())
    .then(response => {
        console.log(this) // <== Window object reference
        if (response.error === 0) {
            console.log('insert ok');
            insertRows++;
        } else {
            if (response.error == 2) {
                console.log('insert error => update');
                var updateEP = baseEP + '/customer/update';
                fetch(updateEP, fetchOptions) // <== Not what you expect 
                .then(updResponse => updResponse.json())
                .then(updResponse => {
                    if (updResponse.error === 0) {
                        console.log('update ok.')
                        updateRows++;
                    } else {
                        console.log('update error: ' + updResponse.msg)
                        errorMessages.push(updResponse.msg);
                    }
                })
                .catch(error => {
                    console.log('update failure');
                    errorMessages.push(error);
                });
            } else {
                console.log('insert error.');
                errorMessages.push(response.msg);
            }
        }
    })
    .catch(error => {
        console.log('insert failure.');
        errorMessages.push(error);
    });
}

我需要一些方法来访问这个fetch调用请求对象来实现这样的事情:

var updFetchOptions = {
    method: "POST",
    cache: "no-cache",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
    },
    redirect: "error",
    referrer: "ux-import", 
    body: this.request.body, // this as a reference to this fetch's request
}
fetch(updateEP, updFetchOptions)...
:
:
答案

你能试试吗?

for (let i = 0; i < expectedRows; i++) {
    let row = myArray[i];
    customerCode = row['customer_code'];
    customerName = row['customer_name'];
    customerBalance = row['customer_balance'];
    // Build body call
    let callBody = {
        user: 'USER',
        code: customerCode,
        name: customerName,
        balance: customerBalance
    };
    let fetchOptions = {
        method: "POST",
        cache: "no-cache",
        headers: {
            "Content-Type": "application/x-www-form-urlencoded",
        },
        redirect: "error",
        referrer: "ux-import", 
        body: JSON.stringify(callBody),
    };
    // Call
    let epurl = baseEP + '/customer/create';
    fetch(epurl, fetchOptions)
    .then(response => response.json())
    .then(response => {
        console.log(this) // <== Window object reference
        if (response.error === 0) {
            console.log('insert ok');
            insertRows++;
        } else {
            if (response.error == 2) {
                console.log('insert error => update');
                let updateEP = baseEP + '/customer/update';
                fetch(updateEP, fetchOptions) // <== Not what you expect 
                .then(updResponse => updResponse.json())
                .then(updResponse => {
                    if (updResponse.error === 0) {
                        console.log('update ok.')
                        updateRows++;
                    } else {
                        console.log('update error: ' + updResponse.msg)
                        errorMessages.push(updResponse.msg);
                    }
                })
                .catch(error => {
                    console.log('update failure');
                    errorMessages.push(error);
                });
            } else {
                console.log('insert error.');
                errorMessages.push(response.msg);
            }
        }
    })
    .catch(error => {
        console.log('insert failure.');
        errorMessages.push(error);
    });
}

基本上,使用var定义变量不是一个好方法,因为它不会在循环的每次迭代中保持其状态。但是使用let维护每次迭代的变量状态,即使在你的情况下执行像fetch这样的异步任务之后你也可以使用变量。

以上是关于如何在fetch then / response函数中访问请求对象的主要内容,如果未能解决你的问题,请参考以下文章

如何在本机反应中进行条件渲染

fetch().then() 返回内容类型和正文 [重复]

我能以某种方式在第一个“then”中获得 fetch 响应吗?

如何在本机反应中解析json数据

如何在使用API 时通过reactjs传递JsonWebToken x-access-token?

React Native,Fetch和Dispatch:如何在mapDispatchToProps()中访问responseData?