在For循环

时间:2018-04-25 13:41:47

标签: node.js reactjs rest post fetch

我有以下功能,旨在删除表格中的所有元素 每行的关键字段存储在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但没有删除数组中的下两个项目,知道为什么这个迭代不起作用?

1 个答案:

答案 0 :(得分:2)

很可能fetch不会解析或抛出错误。由于等待此语句,其他代码的执行永远不会发生。

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

&#13;
&#13;
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]);
        }
    })
}
&#13;
&#13;
&#13;