2017-06-19 13 views
1

私のノードjsコードで関数の同期呼び出しをしようとしています。ノードjsの同期関数呼び出し

私は)私が(私のSET_AUTHENTICATION()関数はset_fileその後、完全に最初に実行しなければならないことをしたい、この

set_authentication(); 
set_file(); 

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

ように私の関数を呼び出すのですSET_AUTHENTICATIONのコールバックの前に実行を開始する実行が、set_file()関数を起動する必要があります()。

私も

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

プロミス1にはないがあなたが作成した約束を返さなかったので働きます。また、 'set_file()、console.error)'を持っています。 '(set_file、console.error)' –

答えて

1

set_authenticationがasync funcの場合、set_authentication関数のコールバックとしてset_fileを渡す必要があります。

書いたように約束を使用することも考えられますが、連鎖を開始する前に約定を実装する必要があります。

+0

set_fileをコールバックとして渡してみて、set_authenticationから呼び出してみました。私のset_fileはまだコールバック関数の前に呼び出されています。 – user3649361

3

あなたが返さ約束の.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); 
 
}

+0

こんにちはありがとうございますが、私のset_authentication()関数内にコールバック関数があります。関数set_authentication(){ callbackFunction();新しい約束を返す(決意=> { たsetTimeout(関数(){ はconsole.log( 'SET_AUTHENTICATION()と呼ばれる'); 解決( "成功!");} 、250); }); }まだ私のset_file()はコールバック関数の前に実行されます。 – user3649361

+0

例に注意してください。 'callbackFunction'は' new 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) 

       } 
      ); 
関連する問題