在 JS 循环中调用以太坊智能合约函数不同步

Calling Ethereum Smart contract function inside a JS loop is not synchronize

我有一个智能合约,它具有 returns 一些基于存储数据的值的功能。函数定义如下

 function getPaperValues(uint _paperId) public view returns(string memory title,string memory ipfscid,address author,PaperStatus status,address[] memory reviewers,bytes32[] memory keywords,uint version)
{
    return (paperFiles[_paperId].title,paperFiles[_paperId].ipfs_cid,paperFiles[_paperId].author,paperFiles[_paperId].status,paperFiles[_paperId].reviewers,paperFiles[_paperId].keywords, paperFiles[_paperId].version_number);
}

如果我通过 javascript 调用它,它工作得很好,但我有一种情况,我必须在 for 循环下的 javascript 中调用这个函数。问题是参数是 "index" 当我把这个提供给 paperContractObj.getPaperValues 它 returns 我是对的来自区块链的值,但参数 "Index" 值已更改。该函数似乎未与其调用时间和结果时间正确同步。

                for (loop = 0; loop < result.length-1; loop++)
                {

                    var index = result[loop];
                    // this function takes index and return correct values as per associated index
                    paperContractObj.getPaperValues(index,{from:account},function (err, result2) {

                    // On this line index value shows different values even though result I received inside result2 is associated with the correct index.  

                    console.log("loop: -"+index); //need to fix this part loop id not coming properly it shows 

                        if (err) {
                            console.log("CALL-ERROR-REASON: "+JSON.stringify(err));
                            console.log("REASON: Unable to retrieve Paper values by Ids");
                        }
                        else {
                            console.log("CALL-SUCCESS: "+JSON.stringify(result2));
                            console.log("CALL-ACHIEVE: Recieved current papers values via ids successfully"+result[loop]);
                            addListHtmlDivs(result2,index); 
                            // Here values from the chain is coming fine but index which was provided as a parameter to this function is changed or different

                        }
     });

                }

我怎样才能确保这个合约函数中的参数不会因为 for 循环而改变。

异步调用合约函数

就放

await

在你的函数调用之前

paperContractObj.getPaperValues

问题已解决,在循环中使用常量索引

for (loop = 0; loop < result.length-1; loop++)
{

                    const index = result[loop];

即使在基于事件的合约函数调用结果中,使用 const 也会给出正确的值。