上週我已經開始在Node.js中進行編碼。我已經寫了代碼來生成JSON查詢多個表和not sure if this is correct way of coding asynchronously
Node.js - 使用多個查詢異步構建JSON
build_actor(post, function(actor){
build_post_object(post, function(post_object){
build_post_attachments(post, function(attachments){
build_post_comments(post, function(comments){
var post_obj = {};
post_obj.actor = actor;
post_obj.object = post_object;
post_obj.attachments = attachments;
post_obj.comments = comments;
console.log(JSON.stringify(post_obj)); // generates JSON
});
});
});
});
function build_actor(post, callback){
//query
callback(actor);
}
function build_post_object(post, callback){
//query
callback(post_object);
}
function build_post_attachments(post, callback){
//query
callback(attachments);
}
function build_post_comments(post, callback){
//query
callback(comments);
}
請讓我知道是否有寫多個查詢,並建立一個JSON一個更好的辦法。
看看異步庫https://github.com/caolan/async。然後你可以整齊地調用所有的函數(如果它們是相互依賴的)或者並行,然後等待所有函數完成。 async.parallel似乎是一個完成方法的選擇的武器,它實際上取得了完整的結果,並對它做了一些事情。 – Todilo
這就是我想要的:)謝謝:) –