为什么在 Node.js 中的子进程上使用 promise 或 async/await?

Why use promise or async/await on child processes in Node.js?

我正在使用子进程 exec,根据文档我认为它是异步的,运行 我的 Node.js 服务器中的 Python 脚本。

然而,当我在网络和 Stack Overflow 上搜索时,我看到许多在 Node.js.[=21= 中使用 promises 和 async/await 作为子进程的实例]

这让我很好奇,如果子进程(execexecFilespawnfork)已经是异步函数,你为什么要使用 promises 或 async/await

这真的取决于您的需要..请在下面的代码中找到有关 async/await

的说明
Without async/await
function (){
      rs = f1(); 
      rs1 = f2();  // this function executes without waiting for f1() 
      return rs + rs1;
}

With async/await
function (){
      rs = await f1();   
      rs1 = f2();        // this function call wait untill f1() executes
      return rs + rs1;
}

Why would you want to use promises or async/await on them?

by "them",你的意思是子进程,是的,子进程是异步的。那么我们可以问这个问题:

Why would you want to use promises or async/await on asynchronous function?

一个原因是为了避免callback hell,通过使它们看起来同步来使编码结构易于阅读。

函数执行有两种类型:同步和异步。

异步函数的调用方式有3种:callback、promises、async/await。

希望对您的理解有所帮助。

我想在之前的答案中添加一些考虑因素,为什么不使用确实使用异步函数(setTiemout、setInterval 等)的回调作为子进程,以及为什么有时您可以找到更多 Promises 或 async/await 模式。这些在此处有很好的描述 https://exploringjs.com/impatient-js/ch_promises.html:

  • 基于Promise的函数和方法的类型签名更清晰:如果一个函数是基于回调的,一些参数是关于输入的,而最后的一两个回调是关于输出的。使用 Promises,所有与输出相关的内容都通过返回值处理。

  • 链接异步处理步骤更方便。

  • Promise 处理异步错误(通过拒绝)和同步错误:在 new Promise()、.then() 和 .catch() 的回调中,异常被转换为拒绝。相反,如果我们使用回调实现异步,通常不会为我们处理异常;我们必须自己做。

  • Promises 是一个单一的标准,它正在慢慢取代几个相互不兼容的替代方案。例如,在 Node.js 中,许多功能现在可以在基于 Promise 的版本中使用。并且新的异步浏览器 API 通常是基于 Promise 的。