在节点js中同步函数调用

我正在尝试对我的节点js代码中的函数进行同步调用。

我打电话给我这样的function

set_authentication(); set_file(); function set_authentication(){ --- callback function --- } 

我希望我的set_authentication()函数应该完全执行,然后set_file()应该开始执行,但set_file()函数在set_authentication()的callback之前开始执行。

我已经尝试使用asynchronous也像

 async.series( [ // Here we need to call next so that async can execute the next function. // if an error (first parameter is not null) is passed to next, it will directly go to the final callback function (next) { set_looker_authentication_token(); }, // runs this only if taskFirst finished without an error function (next) { set_view_measure_file(); } ], function(error, result){ } ); 

但它也不起作用。

我也试过诺言

 set_authentication().then(set_file(),console.error); function set_authentication(){ --- callback function var myFirstPromise = new Promise((resolve, reject) => { setTimeout(function(){ resolve("Success!"); }, 250); }); --- } 

在这里我得到这个错误: – 不能读取未定义的属性'然后'。

我是节点和js的新手。

你需要返回Promise ,因为你调用了.then返回的promise的方法:

 set_authentication().then(set_file); function set_authentication() { return new Promise(resolve => { // <------ This is a thing setTimeout(function(){ console.log('set_authentication() called'); resolve("Success!"); }, 250); }); } function set_file(param) { console.log('set_file called'); console.log( 'received from set_authentication():', param); } 

如果set_authentication是asynchronousfunc,则需要将set_file作为callback函数传递给set_authentication函数。

您也可以考虑使用承诺,但您需要在开始链接之前实施它。

像这样使用async.auto

  async.auto( { first: function (cb, results) { var status=true; cb(null, status) }, second: ['first', function (results, cb) { var status = results.first; console.log("result of first function",status) }], }, function (err, allResult) { console.log("result of executing all function",allResult) } );