[英]How to handle modules in an asynchronous app in node.js
for (var i = 0; i < users.length; i++) {
if (users[i].access_token !== undefined) {
var syncer = require('dropsite_server/dbox_sync');
var client = dboxApp.client(users[i].access_token);
var websites_to_sync = [];
syncer.doSync(client, users[i].website, users[i].access_token.uid);
}
}
在syner.doSync中,我有一些異步函數調用。 是的,出於性能方面的考慮,我想讓它們保持異步。 問題在於,同步器對象只是一個引用,因此在doSync工作時,for循環將繼續運行,然后更改變量。
現在,周圍的for循環只有兩個元素,結果是僅處理了最后一個元素,但不僅處理了一次,而且實際上處理了兩次。
解決方案是使同步器成為適當的對象,但是以某種方式我失敗了。 為了更好地了解同步器中的代碼的外觀,請從以下開始:
/**
* This here is the sync module. User needs to provide. All this module does,
* is sync from a users dropbox to a local path
*/
var dbox = require("dbox");
var fs = require("fs");
var async = require("async");
var allow_downloads = true;
var allow_local_deletes = true;
var client = null;
var saved_sync_data = null;
var sync_data_path = global.config.sync_data_file;
var uid = null;
var remote_sync_dirs = null;
//var sync_data_file = ".dropbox_sync_data";
var errors = [];
var queue = async.queue(doTask, 1);
exports.doSync = function (clientIn, website_domain, _uid) {
client = clientIn;
uid = _uid;
sync_data_path = sync_data_path + "_" + uid;
remote_sync_dirs = website_domain;
async.series(
[
readSyncDataFile,
startSync
]);
}
/**
* Start the Sync
* @param dbox client This is a dbox client
*/
function startSync() {
console.log("get remote delta for website: " + remote_sync_dirs)
getRemoteDelta();
}
var聲明的作用域不是循環,而應在文件/函數的頂部進行
var syncer = require('dropsite_server/dbox_sync')
, client
, websites_to_sync = [] //what is this used for?
for (var i = 0; i < users.length; ++i) {
if (users[i].access_token !== undefined) {
client = dboxApp.client(users[i].access_token)
syncer.doSync(client, users[i].website, users[i].access_token.uid);
}
}
最后一項被處理兩次的原因是doSync函數設置模塊級別的變量,每次調用該變量都會被覆蓋。
解決此問題的方法是將變量傳遞給函數
exports.doSync = function (client, website_domain, uid) {
sync_data_path = sync_data_path + "_" + uid
remote_sync_dirs = website_domain
async.series([
readSyncDataFile.bind(null, client, website_domain, uid)
, startSync.bind(null, client, website_domain, uid)
])
}
function startSync(client, website_domain, uid) {
...
}
function readSyncDataFile(client, website_domain, uid) {
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.