【问题标题】:How to access the request object in a fetch then/response function如何在 fetch then/response 函数中访问请求对象
【发布时间】:2019-02-09 14:59:11
【问题描述】:

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

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

有什么方法可以访问用于此获取操作的请求对象,以便我可以使用该对象而不是循环变量?

我尝试在 promise 方法中使用 this,但它返回对窗口对象的引用: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)...
:
:

【问题讨论】:

    标签: javascript asynchronous request fetch


    【解决方案1】:

    你可以试试这个。

    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 之类的异步任务之后,您也可以使用该变量。

    【讨论】:

      猜你喜欢
      • 2015-02-20
      • 2021-07-04
      • 1970-01-01
      • 2014-11-18
      • 1970-01-01
      • 2012-03-10
      • 2020-06-25
      • 2022-12-06
      • 2021-07-27
      相关资源
      最近更新 更多