2017-06-19 68 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) 

       } 
      );