javascript 在函数中创建Node.js任务

s4n0splo  于 2022-12-02  发布在  Java
关注(0)|答案(1)|浏览(145)

我可以在每个任务都找到函数而不是所有任务都完成时,生成任务来并行运行函数并返回值吗?如果可以,我需要什么来生成任务并在完成后返回?
我要并行运行的示例函数:

function example(){
    do{
        axios.get(url).then(result => {
            if(result.data == "success"){
                console.log(result.data)
                return i = 1;
            }
            else{i = 0;}
        }
    }
    while (i < 1);
}

老实说,我不知道从哪里开始。我看过Youtube上关于集群的视频,使用基于承诺的数组Map等。希望能更清晰一些

z9ju0rcb

z9ju0rcb1#

可以使用Promise.all()并行运行多个异步任务,并在所有任务完成后返回结果数组。下面是一个示例,说明如何执行此操作:

function example() {
  return new Promise((resolve, reject) => {
    do {
      axios.get(url)
        .then(result => {
          if (result.data == "success") {
            console.log(result.data);
            resolve(1);
          } else {
            resolve(0);
          }
        })
        .catch(err => reject(err));
    } while (i < 1);
  });
}
    
// Spawn multiple tasks to run the example function in parallel
const tasks = [
  example(),
  example(),
  example()
];
    
// Use Promise.all() to run the tasks in parallel and return the results when each task has completed
Promise.all(tasks)
  .then(results => {
    // handle the results of the example() function here
  })
  .catch(err => {
    // handle any errors here
  });

这里我们将example()函数定义为Promise函数,当axios.get()请求成功时,Promise函数解析为result.data值,如果请求不成功,Promise函数将拒绝并返回错误。然后,我们创建一个任务数组,每个任务都调用example()函数。
最后,我们使用Promise.all()方法并行运行任务,并在所有任务都完成时返回结果。Promise.all()方法返回一个Promise,当所有任务都成功完成时,该Promise用一个结果数组进行解析,或者在出现第一个错误时拒绝。
您可以使用此模式并行运行多个任务,并在每个任务完成后返回结果。但是,请记住,如果任何任务失败,Promise.all()方法将拒绝,因此您应该在代码中适当地处理错误。

相关问题