【问题标题】:React how to make POST request in For Loop反应如何在 For 循环中发出 POST 请求
【发布时间】:2018-04-25 13:41:46
【问题描述】:

我有以下功能,旨在删除表中的所有元素。
每行的key字段存储在rowKeys中,当前内容为["www.google.com", "www.youtube.com", "www.facebook.com"]

async onAfterDeleteRow(rowKeys) {
    for(let i = 0; i < rowKeys.length; i++){
        console.log(rowKeys.length);  //3
        console.log(rowKeys[i]);  //www.google.com

        this.setState({
            deleting: true,
            jsonBefore: this.state.json
        });

        console.log("About to post");  //About to post

        const response = await
            fetch('/delete-cert', {
                headers: {
                    'Content-Type': 'application/json'
                },

                method: 'POST',
                body: JSON.stringify({deletedCert: rowKeys[i]})
            });

        console.log("Post done");

        const body = await response.text();
        if (response.status !== 200) throw Error(body.message);
    }

    console.log("Left For Loop");
}

以下 3 行打印到控制台:

3  
www.google.com  
About to post  

但它不会打印 2 行:

Post done  
Left For Loop

它成功删除了www.google.com,但没有删除数组中的下两个项目,知道为什么这个迭代不起作用吗?

【问题讨论】:

  • 首先将这些等待包装在 try catch 块中

标签: node.js reactjs rest post fetch


【解决方案1】:

很可能 fetch 无法解析或引发错误。由于您等待此语句,因此将永远不会执行其他代码。

更好的做法是触发所有请求并等待所有请求完成(请参阅Promise.all())。

async onAfterDeleteRow(rowKeys) {
    // a list of all request promises
    let requests = [];
    
    for(let i = 0; i < rowKeys.length; i++){
        console.log(rowKeys.length);  //3
        console.log(rowKeys[i]);  //www.google.com

        this.setState({
            deleting: true,
            jsonBefore: Kthis.state.json
        });

        requests.push( 
            fetch('/delete-cert', {
                headers: {
                    'Content-Type': 'application/json'
                },

                method: 'POST',
                body: JSON.stringify({deletedCert: rowKeys[i]})
            }).then(async (response)=>{
                const body = await response.text();
                if (response.status !== 200) throw Error(body.message);
                // if everything is fine resiolve to true or for example your body content
                return Promise.resolve(true);
            }).catch((e)=>{
                // if we encounter an error resolve to false
                console.error('there was an error:', e.message)
                return Promise.resolve(false);
            })
        )
    }
    console.log("Left For Loop");

    // wait until all requests are done!
    await Promise.all(requests).then((results)=>{
        // here we have all the results
        console.log('all requests finished!', results);
        for(let i = 0; i < requests.length; i++){
          console.log(i, 'request resultet in', results[i]);
        }
    })
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-06
    • 2018-06-11
    • 1970-01-01
    • 2016-11-13
    • 2021-12-25
    • 2019-08-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多