2017-08-11 6 views
1

私はNode.jsを初めて使用しています。私は以下のようにデータベースからデータを読み込むためにDynamoDBローカルを使用しています。node.js:非同期データをグローバルに利用できるようにする方法

function readFromTable (params){ 

    docClient.get(params, function(err, data) { 
     if (err) { 
      console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); 

     } else { 
      console.log("GetItem succeeded:", JSON.stringify(data, null, 2)); 
      result = JSON.stringify(data, null, 2); 
      console.log ("got result"); 
      console.log (result); 
     } 
    }); 

私は非同期機能であることを理解することはできません。非同期データは、関数successイベント内でのみ使用できます。

しかし、私はhtmlに返す必要があるので、関数の外でresultデータを利用できるようにする必要があります。それ、どうやったら出来るの?

答えて

2

私は約束を使用することをお勧めします。ここにあなたのコードがあります。

function readFromTable(params) { 
    return new Promise((resolve, reject) => { 
    docClient.get(params, function(err, data) { 
     if (err) { 
      console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2)); 
      return reject(err); 
     } else { 
      console.log("GetItem succeeded:", JSON.stringify(data, null, 2)); 
      result = JSON.stringify(data, null, 2); 
      console.log ("got result"); 
      return resolve(result); 
     } 
    }); 
    }); 
} 

readFromTable(yourParams).then((results) => { 
    console.log('You got your results'); 
}); 
1

答えはコールバックまたは約束です。すべての変数は関数 'docClient'内でアクセスできます。コールバックの簡単な例を考えてみましょう。

function readFromTable (params) { 

    function anotherFunction(callback) { 
     //do something 
     var someVariable = ''; 
     callback(someVariable); 
    } 

    docClient.get(params, function (err, data) { 
     if (err) { 
      console.log(err); 
     } else { 
      anotherFunction(function (someVariable) { 
       console.log(someVariable); 
       // you can access data here; 
       console.log(data); 
      }) 
     } 
    }) 
}; 

私は助けてくれることを願っています。

関連する問題