Node js - 通过循环同步执行函数

Node js - Synchronous execution of functions through loop

我有如下代码

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函数需要response一个数组的值,应该通过循环来实现。但是由于节点 js 的异步特性,callWebSocket 函数在响应到来之前被调用。但是我有一个使用服务器端脚本的用例,我选择了节点 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' }
  });
}