Nodejs-通过循环同步执行函数



我有一个类似以下的代码

function getData()
{
for(var i=0; i<someLength; i++)
{
if(i===0)
{
response = callApi(someValue[i]);
}
else if(i===1)
{
responseInsert = callWebSocket(response, someValue[i]);
}       
}
}
function callApi(insertData)
{
axios({
method: 'post',
url: 'http://localhost:1130/services/request',
data: insertData,
headers: { 'content-type': 'application/xml;charset=utf-8' }
}).then(function (response) {
console.log(response);
retVal = true;
return retVal;
}).catch(function (error) {
console.log(error);    
});
}

在这种情况下,需要对具有数组值的callWebsocket函数进行响应,这应该通过循环来实现。但是由于节点js的异步特性,callWebSocket函数在响应到来之前被调用。但是我有一个使用服务器端脚本的用例,我选择node.js。任何与循环同步执行功能的帮助都会节省我的时间。

您需要稍微修改一下callApi方法。试试这个:

async function getData()
{
for(var i=0; i<someLength; i++)
{
if(i===0)
{
response = await callApi(someValue[i]);
}
else if(i===1)
{
responseInsert = callWebSocket(response, someValue[i]);
}       
}
}
function callApi(insertData)
{
return axios({
method: 'post',
url: 'http://localhost:1130/services/request',
data: insertData,
headers: { 'content-type': 'application/xml;charset=utf-8' }
});
}

最新更新