【问题标题】:How to make the rest of code wait in fun1 until fun2() finishes, where fun2 is a nested function in fun1?如何让其余代码在 fun1 中等待直到 fun2() 完成,其中 fun2 是 fun1 中的嵌套函数?
【发布时间】:2021-04-11 21:05:42
【问题描述】:
fun1()
{
 for()     //fun1 making api calls in loop
 {
  https.get()
  {
    ..
    ..
    fun2();   //Invoking fun2
    fu2()
    {
      for()   //fun2 also making api calls in loop
     {
      https.get()
      {
        ..
        ..
      }
    }}
  }
}
}

代码异步运行,我怎样才能让它逐行运行,这意味着直到 fun2() 代码完成 fun1 中的其余代码时不必执行。 fun1 必须等到 fun2 完成。

我认为这将通过 async-await 解决,但不知道该怎么做。有人可以帮我吗

【问题讨论】:

标签: javascript node.js asynchronous async-await promise


【解决方案1】:

我不会使用循环。

async function fun1() {
  async function fun2() {
  //...
  }
  await Promise.all([...Array(10).keys()].map((i) => { fun2() })
}

但如果你真的喜欢你的循环

async function fun1() {
  async function fun2() {
  //...
  }
  const promises = []
  for(...) {
    promises.push(fun2())
  }
  await Promise.all(promises)
}

【讨论】:

    【解决方案2】:
    Vulwsztyn,
    Thanks for helping me on this issue. 
    But the solution which u provided, that iam not able to insert properly into my code and also i didn't asked asked the ques with proper code. 
    
    
    Here is the my code which iam using. In this code Iam using three console.log's for printing
    
    1.console.log("Fun1 Api Response======",jsonParsedArray2);
    2.console.log("Fun2 Api Response======",jsonParsedArray5);
    3. console.log("result="+result)
    
    If iam able to get the output in this order 
    
    console.log("Fun1 Api Response======",jsonParsedArray2);
    console.log("Fun2 Api Response======",jsonParsedArray5); 
    console.log("result="+result);
    console.log("Fun1 Api Response======",jsonParsedArray2);
    console.log("Fun2 Api Response======",jsonParsedArray5);
    console.log("result="+result);
    ...
    ....
    ...
    
    then i can assure my code is running sequentially.
    
    Could u please edit this code with async.await, bcoz idont know much about async.await and where to add it correctly.
    
    Normally iam getting o/p like this :
    
    console.log("Fun1 Api Response======",jsonParsedArray2);
    console.log("Fun1 Api Response======",jsonParsedArray2);
    console.log("Fun1 Api Response======",jsonParsedArray2);
    console.log("result="+result)
    console.log("Fun2 Api Response======",jsonParsedArray5);
    console.log("Fun2 Api Response======",jsonParsedArray5);
    console.log("Fun2 Api Response======",jsonParsedArray5);
    
    Thank you
    
    ========CODE=======
    //First Function
    
    function getDetailsOfEachProxy(maxRevisionNumberOfEachApiArray,mailArray,hostName,reqHeaders,callback){
        setTimeout(()=>{
        for(z=0;z<mailArray.length;z++)   
            {
                let options = {
                  hostname: hostName,
                  path: "/v1/organizations/orgname/apis/"+mailArray[z]+"/revisions/"+maxRevisionNumberOfEachApiArray[z],
                  method: "GET",
                  headers: { 
                      "Authorization": reqHeaders
                  }
                }
                https.get(options, (res) => {
                  res.setEncoding('utf8');
                  let data1='';
                  res.on('data', (chunk) => {
                    data1 += chunk;
                  })
                  res.on('end', () => {    
                        jsonParsedArray2 = JSON.parse(data1);
                         console.log("Fun1 Api Response======",jsonParsedArray2);
                        for (key in jsonParsedArray2) {
                            if (jsonParsedArray2.hasOwnProperty(key))
                            {
                                listOfElementsArray[j] = jsonParsedArray2[key];
                                j=j+1;
                                var apiBasePath = listOfElementsArray[0];
                                 var apiName = listOfElementsArray[11];
                                var apiProxies = listOfElementsArray[12];
                                var proxyEndPointElement = listOfElementsArray[13];
                                var proxyResources = listOfElementsArray[16];
                                 var proxyRevision = listOfElementsArray[17];
                                var targetEnPointElement = listOfElementsArray[22];  
                            } 
                            }
                            for (key2 in apiProxies){
                                apiProxyArray[t] = apiProxies[key2];
                                t++;  
                                }
                            for (key2 in proxyEndPointElement){
                                var proxyEndPoint = proxyEndPointElement[key2];
                                }
                            for (key2 in proxyResources){
                                proxyResourcesArray[t2] = proxyResources[key2];
                                t2++;
                                rotation1++;   
                                }  
                            for (key2 in targetEnPointElement){
                                var targetEndPoint = targetEnPointElement[key2];
                                }
                                         
                    for(i=0;i<apiProxyArray.length;i++)
                    {
                    f = apiProxyArray[i];
                    if (f.startsWith('FC-'))
                    {
                    flowCalloutPolicyArray[fcpa] = f;
                    fcpa++;
                    }                  
                    f='';
                    }
    
                    for(i=0;i<apiProxyArray.length;i++)
                    {
                    f2 = apiProxyArray[i];
                    if(f2.startsWith('KVM-'))
                    {
                    kvmPolicyArray[kpa] = f2;
                    kpa++;
                    }                
                    f2='';
                    }
                                
    //Invoking Second Fun inside First Fun        
       getSharedFlows(apiName,proxyRevision,hostName,reqHeaders,flowCalloutPolicyArray,function(result)
                            {
                     console.log("result="+result)
                                });
    
    //Second Function
    
    function getSharedFlows(apiName,proxyRevision,hostName,reqHeaders,flowCalloutPolicyArray,callback){ 
    if(flowCalloutPolicyArray.length > 0)
    {    
            for(iim=0;iim<flowCalloutPolicyArray.length;iim++)
            {
             let options = {
                 hostname: hostName,
                 path:  "/v1/organizations/orgname/apis/"+apiName+"/revisions/"+proxyRevision+"/policies/"+flowCalloutPolicyArray[iim],
                 method: "GET",
                 headers: { 
                     "Authorization": reqHeaders
                 }
               }
               https.get(options, (res) => {
                 res.setEncoding('utf8');
                 let data4='';
                 res.on('data', (chunk) => {
                   data4 += chunk;
                 })
                 res.on('end', () => {    
                       jsonParsedArray5= JSON.parse(data4);
                      console.log("Fun2 Api Response======",jsonParsedArray5);
                        }) //res.on
                    });//http.get
       }//for
              callback("successfully executing code line by line")
        }//if
        sfbv = 0;
     }//fun
    
     
    
                                    j=0;
              
              flowCalloutPolicyArray.length=0;
              fcpa=0;
              apiProxyArray.length=0;
              t=0;
              proxyResourcesArray.length=0;
              t2=0;
              sharedFlowElement = '';
              //sharedFlowBundleValue ='';
              
              kvmPolicyArray.length = 0;
              kpa = 0;
              kvmElement = '';
    
              
    
      
                })//CLOSING INTERNAL res.on function
                // console.log('Number of developers having certficate=',certsArray.length)
                
              });//CLOSING INTERNAL https FUNCTION
              //LOOP ROTATE UPTO HERE ONLY 
                   
            }//FOR LOOP END 
        },5500);  
    }//END OF FUNCTION
    

    【讨论】:

      猜你喜欢
      • 2016-12-23
      • 2022-01-24
      • 2021-08-31
      • 2020-01-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-30
      • 2019-03-15
      相关资源
      最近更新 更多