2016-03-21 18 views
0

私はnode.jsの非同期プロパティとコールバックの力についてたくさんの読んだことがあります。関数外のNode.js変数スコープ

しかし、私が関数を定義し、その関数内の変数の値を変更した場合、なぜ関数外で利用できないのか分かりません。

私が取り組んでいるコードの例を示してみましょう。

var findRecords = function(db, callback) { 

var cursor =db.collection('meta').find({"title":"The Incredible Hulk: Return of the Beast [VHS]"}, {"asin":1,_id:0}).limit(1); 
pass=""; 
cursor.each(function(err, doc) { 
     assert.equal(err, null); 
     if (doc != null) { 
      var arr = JSON.stringify(doc).split(':'); 
      key = arr[1]; 
      key = key.replace(/^"(.*)"}$/, '$1'); 
      pass =key; 
      console.log(pass); //Gives correct output 
     } 

    }); 

    console.log(pass) //Does not give the correct output 

}; 



MongoClient.connect(url, function(err, db) { 
    assert.equal(null, err); 

    findRecords(db, function() { 
     db.close(); 
    }); 
}); 

ここでは関数内でパスの値を印刷する際には、割り当てられた新しい価値を提供しますが、関数の外二回目の印刷時には、新たな価値を与えるものではありません。

どのようにしてこの問題を解決できますか。

+0

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures –

答えて

0

代わりにpass = ""
これを宣言し、これを試してください。var pass = "";

+0

。 – Arqam

1
let pass = 'test'; 

[1, 2, 3].map(function(value) { 
    let pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

console.log(pass); // => test 

// ------------------------------ 

let pass = 'test'; 

[1, 2, 3].map(function(value) { 
    pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

// the last value from the iteration 
console.log(pass); // => 3 

// ------------------------------ 

// we omit the initial definition 

[1, 2, 3].map(function(value) { 
    // note the usage of var 
    var pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

// the variable will exist because `var` 
console.log(pass); // => 3 

// ------------------------------ 

// we omit the initial definition 

[1, 2, 3].map(function(value) { 
    // note the usage of var 
    let pass = value; 
    // local scope: 1, 2, 3 
    console.log(pass); 
}); 

// the variable will not exist because using let 
console.log(pass); // => undefined 
1

使用してみてください:動作しません

var pass=""; 
var that = this; 
cursor.forEach(function(err, doc) { 
     assert.equal(err, null); 
     if (doc != null) { 
      var arr = JSON.stringify(doc).split(':'); 
      key = arr[1]; 
      key = key.replace(/^"(.*)"}$/, '$1'); 
      pass =key; 
      console.log(pass); //Gives correct output 
     } 

    }, that); 
console.log(pass);