等待服务器的响应以继续程序。

huangapple go评论61阅读模式
英文:

Waiting for response from the server to continue the program

问题

对于我的生物信息学工作,我想要构建一个与Node.js服务器(Express)连接的React应用程序。

想法是客户端选择他们需要分析的样本,然后服务器会处理工作流程。我希望程序在每个样本上执行第一个过程,然后在每个样本上执行第二个过程。

在运行后续过程之前等待过程结束(并从服务器获得积极响应)非常重要。我认为嵌套循环会起作用,但不是这样。

processes.forEach(p => {
    samples.forEach(s => {
       runProcess()
  })
})

我尝试了async/await方法,但没有成功。

英文:

For my bioinformatics work, I want to build a React app, connected to Node.js server (Express).

The idea is that the client picks the samples they need to analyse, and the server would process the workflow. I want the program to execute process one on each sample, after that process two on each sample.

It's very import to wait for the process to end (and get a positive response from the server) before running the following process. I thought a nested loop would work, but no.

processes.forEach(p => {
    samples.forEach(s => {
       runProcess()
  })
})

I tried the async/await method, but without success.

答案1

得分: 1

forEach 不支持异步,而 for 循环可以支持异步调用。你可以尝试像这样写:

const wait = (time) => new Promise(resolve => {
  setTimeout(resolve, time)
});

async function runCode() {
  const arr = [1,2,3,4]
  for (let i = 0; i < arr.length; i++) {
    // 开始你的请求
    await wait(3000)
    // 请求完成后,下一个请求将开始
    console.log('item', i);
  }
}

runCode()
英文:

forEach does not support asynchronous, for loop can support asynchronous calls. you can try like this.

    const wait = (time) =&gt; new Promise(resolve =&gt; {
      setTimeout(resolve, time)
    });

    async function runCode() {
      const arr = [1,2,3,4]
      for (let i = 0; i &lt; arr.length; i++) {
        // start your request 
        await wait(3000)
       // request finished then next will start
        console.log(&#39;item&#39;, i);
      }
    }

    runCode()

huangapple
  • 本文由 发表于 2023年5月11日 16:06:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/76225386.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定