2017-06-19 71 views
1

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

我打电话给我的功能,这样

set_authentication(); 
set_file(); 

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

我想,我的set_authentication()函数应首先执行完全,然后set_file()应该开始执行,但set_file()函数开始set_authentication的回调之前执行()。

我曾尝试使用这种异步也喜欢

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。

+0

无极一个不工作,因为你还没有返回你创建的承诺,你也有'然后(set_file(),console.error)',临时工t会立即调用set_file,因为你有'()',它告诉它调用它而不是将它作为参考传递:'then(set_file,console.error)' –

回答

1

如果set_authentication是异步函数,则需要将set_file作为回调函数传递给set_authentication函数。

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

+0

我尝试传递set_file作为回调,并从set_authentication函数,但仍然我的set_file在回调函数之前被调用。 – user3649361

3

您需要返回Promise,因为你调用返回的承诺.then方法:

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); 
 
}

+0

嗨感谢您的答案,但我的set_authentication()函数内有一个回调函数如果我使用这样的东西。函数set_authentication(){ callbackFunction();返回新的Promise(解决方案=> {0} {0} {0} setTimeout(function(){ console.log('set_authentication()called'); resolve(“Success!”); },250); }); }仍然我的set_file()在回调函数之前执行。 – user3649361

+0

请注意这个例子。 'callbackFunction'应该放在方括号内的新Promise(resolve => {HERE})'中。 – terales

0

使用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) 

       } 
      );