2012-07-26 52 views
1

我想將第三方模塊(Patio)的異步函數變成同步函數。node.js - 像許多其他人一樣將異步函數變成同步函數

function get_user_message_list(parameters, array, response) 
{ 
var new_array = []; 
for (var i in array) { 

    var json = array[i]; 
    json['content']['users_seen'] = ["1757842565"]; 
    json['content']['users_not_seen'] = []; 

    new_array.push(json); 
} 

console.log("NEW ARRAY :"); 
console.log(new_array); 

response.writeHeader(200, {'Content-Type':'application/json'}); 
response.end(JSON.stringify(new_array)); 
} 

function get_json_message(parameters, json) 
{ 
console.log("JSON OBJECT :"); 
console.log(json); 
var dataset = db.from(TABLES.USER).join(TABLES.MOVIE_LIST, {MLUserId: sql.URId}).join(TABLES.MOVIE, {MVId: sql.MLMovieId}); 

dataset.where('MLSeen={seen} AND MVSourceId={movie} AND MVSource={source} AND URId!={user}', {seen: 1, movie: json['content']['movie_id'], source: json['content']['movie_source'], user:parameters.FACEBOOK_ID}).all().then(function(users){ 
    if (users) { 
     for (var j in users) { 
      json['content']['users_seen'].push(users[j].URId); 
     } 
    } 

    //console.log(json['content']['users_seen']); 

    dataset.where('MLSeen={seen} AND MVSourceId={movie} AND MVSource={source} AND URId!={user}', {seen: 0, movie: json['content']['movie_id'], source: json['content']['movie_source'], user:parameters.FACEBOOK_ID}).all().then(function(users){ 
     if (users) { 
      for (var j in users) { 
       json['content']['users_not_seen'].push(users[j].URId); 
      } 
     } 

     console.log(json); 
    }, errorHandler); 
}, errorHandler); 
} 

在get_user_message_list函數中,我迭代到一個數組中,併爲每次迭代調用異步函數。在這個異步函數中,我使用Patio模塊向MySQL數據庫發出請求。但是就像你所看到的,我必須等待查詢結果發送給前一個函數後才能得到。

如何將get_json_message轉換爲sync_get_json_message? 謝謝。

回答

2

,你可以和你應該把異步功能到的東西,行爲像同步功能,當出現問題需要修復。你不可能不是正確的答案,程序員不應該回答。

所以,我最近在nodeunit模塊中找到了一些可以幫助你的代碼。它啓動異步功能,跟蹤哪些已準備就緒。在所有請求進入後,觸發回調。這可能是解決問題背後的想法(所以不,這不是最終的解決方案)。

async.forEachSeries = function (arr, iterator, callback) { 
    if (!arr.length) { 
     return callback(); 
    } 
    var completed = 0; 
    var iterate = function() { 
     iterator(arr[completed], function (err) { 
      if (err) { 
       callback(err); 
       callback = function() {}; 
      } 
      else { 
       completed += 1; 
       if (completed === arr.length) { 
        callback(); 
       } 
       else { 
        iterate(); 
       } 
      } 
     }); 
    }; 
    iterate(); 
}; 

該測試觸發我看到它是怎麼做:

exports['series'] = function (test) { 
    var call_order = []; 
    async.series([ 
     function (callback) { 
      setTimeout(function() { 
       call_order.push(1); 
       callback(null, 1); 
      }, 25); 
     }, 
     function (callback) { 
      setTimeout(function() { 
       call_order.push(2); 
       callback(null, 2); 
      }, 50); 
     }, 
     function (callback) { 
      setTimeout(function() { 
       call_order.push(3); 
       callback(null, 3, 3); 
      }, 15); 
     } 
    ], 
    function (err, results) { 
     test.equals(err, null); 
     test.same(results, [1, 2, [3, 3]]); 
     test.same(call_order, [1, 2, 3]); 
     test.done(); 
    }); 
}; 

快樂編程!

+1

這是一個非常短視的答案..這個問題的解決方案會導致更多的問題,而不是解決問題 – 2013-08-15 16:14:55

0

你不能,你不應該。這將有效地阻止您的Node.JS服務器,並且您將失去Node.JS提供的所有優勢。它也違背了Node.JS的整個異步思想。

只是通過callback參數的函數:

function get_json_message(parameters, json, callback){ // <---- note the callback 
    // some other stuff 
    dataset.where(... 
     // some other stuff 
     dataset.where(... 
      // some other stuff 
      // I've finished the job, call the callback 
      callback(); // <--- you can pass additional params here 
     }); 
    }); 
} 

,並調用它像這樣:

get_json_message(params, json, function() { 
    console.log('Hello world!'); 
    // do whatever you like inside callback 
}); 
+5

你假設你運行的是node.js服務器而不是腳本......不要假設。 – fnf 2013-04-01 14:09:33

+0

@fnf夠公平的。這仍然是一個好習慣。 – freakish 2013-04-01 15:18:04

+3

不是一個全面答案的忠實粉絲,也不是說一種語言或框架決定了應該如何做。任何花費一些時間開發真實世界應用程序的人都會遇到這個問題,通常是因爲不使用回調函數的庫,例如expressHelper。 – tempestSA 2013-06-13 00:12:55

0

我一直在使用syncrhonize.js,取得了巨大的成功。甚至有一個待處理的拉取請求(工作得很好)來支持具有多個參數的異步函數。比節點同步imho更好更容易使用。它增加了獎勵,它有易於理解和詳盡的文檔,而節點同步則沒有。