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

6yoyoihd  于 2023-01-01  发布在  Java
关注(0)|答案(2)|浏览(140)

我有一个遍历数组的JavaScript循环。对于每一个项目,我执行一个fetch请求来插入对象。如果服务器响应表明它是一个已经插入的对象,我尝试用另一个fetch调用执行更新操作。
由于请求是异步的,在我尝试更新操作之前,循环将请求对象设置为下一个插入项,因此我最终请求更新一个尚未插入的对象。
是否有任何方法可以访问用于此获取操作的请求对象,以便使用该对象代替循环变量?
我尝试在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)...
:
:
holgip5t

holgip5t1#

你能试试这个吗。

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)之后也可以使用该变量。

hfwmuf9z

hfwmuf9z2#

您可以通过显式创建RequestInit-Object并如下 Package 处理程序函数来实现这一点:

const initObject = {
    method: 'POST',
    something: 1234
};
fetch('/test.json', initObject)
    .then(r => r.json())
    .then(((initObject) => {
        return json => {
            console.log({json, initObject})
        }
    })(initObject));

相关问题