节点阻塞功能包含嵌套的NON阻塞功能?

时间:2017-04-07 17:00:12

标签: javascript mysql node.js

我在我的Node代码中需要从数据库(MySQL)中检索4或5个项目,然后对结果进行一些数学计算,然后将结果返回到调用的代码的主要部分。功能。在我从这些函数或函数返回数据之前,我无法在代码中继续前进。

我读到的所有内容都说不会创建同步功能,因为你带走了使用Node的所有快乐和美丽。但是,我实际上无法继续执行我的代码而没有函数的结果。

那么,我不需要同步功能吗?如果是这样,为什么会这么错? LOL。

我想过做一个同步的大外部函数,它包含实际完成工作的4个或5个函数。我可以使嵌套函数Async并使外部函数(容器)同步。

对此有何想法? Node的新手,并且只是第一次尝试这样做。

1 个答案:

答案 0 :(得分:1)

在继续之前等待几个i / o操作完成是一个常见问题,尤其是节点+数据库。我尽力做到这一点 async尽可能只在程序的逻辑流程绝对要求时阻塞。您对#34;使嵌套函数异步的想法"好像很好。

您可以利用Promise.all启动所有异步内容。如果您等待承诺的结果,它将不会转到下一行代码,直到Promise.all完成

这里有一些代码含有愚蠢但描述性的函数名称,我希望这些代码有用。

async function processIAmTryingToDoAsAsynchAsPossible(allCommandsToExecute) {
  try {
    // go get all the data asynchronously and destructure the results. But only move to the next line
    // once all the async calls have returned
    const [firstResult, secondResult, thirdResult] = await Promise.all(allCommandsToExecute.map(eachCommandToExecute => executeSqlFunction(eachCommandToExecute)));

    // assuming it is just math, this is not an i/o operation so it will execute "synchronously"
    const finalMathProduct = doMathOnThisStuff(firstResult, secondResult, thirdResult);

    // assuming this is an i/o operation and the final function returns something you need
    return await functionWeCallAfterGettingTheData(finalMathProduct);
  } catch (err) {
    // You'll get here if the Promise.all has a reject, if the final function errors out,
    // or if you throw an error in one of the other functions.
    throw err;
  }
}
相关问题