Javascript等待函数结束,包括来自node.js的异步MYSQL查询

Javascript to wait the end of a function including asynchronous MYSQL Queries from node.js?

本文关键字:js node 异步 查询 MYSQL 函数 等待 结束 包括 Javascript      更新时间:2023-09-26

我遇到了Javascript问题,在调用以下行之前等待函数完成。前面的函数包括Javascript MYSQL Query调用(node.js库之一)。然后它将看起来像:

function first() {
    /**
    * a lot processes to execute
    * including Asynchronous processes
    * like running Queries using Javascript MYSQL Library from node.js
    */
    console.log("I am the first one!");
}
first();
console.log("I am the second one!");

然后当我执行这个时,它发生如下:

I am second one!
I am first one!

如何通过保持队列顺序使它们运行?

注意:现在对于所有混淆问题的人,请再次跳转/关注我新创建的问题:每个人都请关注/跳入这个新问题:
节点.js MYSQL 以检测查询的插入/更新完整性?

将第二个函数的回调传递给对第一个函数的调用。 在第一个函数结束时,调用 theh 回调:

function one(parm, callback) {
    // do something
    callback();
}
function two() {
    // do something else
}
one("my parm", two);

您需要构建代码才能使用回调

function first (callback) {
// do your stuff
callback.call();
}
first(function () { console.log("I am the second"; });

> 您遇到的问题在JavaScript之前用其他语言编程的人中很常见,例如c/java,您认为JavaScript会执行以下操作:

 Line of code1. Execute,when it's done go to the next.
 Line of code2. Execute,when it's done go to the next.
 Line of code3. Execute,when it's done go to the next.

JavaScript 中实际发生的事情更像是:

 Line of code1. Execute
 Line of code2. Execute
 Line of code3. Execute

为了使JavaScript按预期工作,您需要以面向事件的方式对其进行编程,这意味着您需要指定要以特定顺序运行的函数。要JavaScript做到这一点,您需要使用 callbacks ,例如:

 function1 (parameter A,function2){
        //...   
        function2(parameter B,function3)} 
 function2 (parameter B,function3){//...} 
 function3 (){//...} 

您可以更多地概括上面的例子,但是我认为这样保留它更容易理解。你可以在网上找到很多关于这个的文章。google搜索的第一个结果给了我这个链接。

祝您编码愉快!