使用回调从dynamodb.getItem()返回数据

时间:2016-03-21 16:51:11

标签: javascript callback

我是js的新手 - 我无法解决如何使用回调从异步操作返回值的问题。这是我当前的代码迭代,它仍然返回'test undefined'。任何人都可以检查我做错了什么?谢谢。任何帮助表示赞赏。

        var test = this.getImgurClientId(function (data) {
            console.log(data.Item.ClientId.S);  //this has a value
            return data.Item.ClientId.S;
        });
        console.log('test ' + test); //prints 'test undefined'



      this.getImgurClientId = function(callback) {
        AWS.config.update({
          accessKeyId: AWS_ACCESSKEYID,
          secretAccessKey: AWS_SECRET_ACCESSKEYID,
          region: AWS_DYNAMODB_REGION
        });

        var dynamodb = new AWS.DynamoDB();

        //console.log(dynamodb);

        var params = {
          AttributesToGet: [
            "ClientId"
          ],
          TableName: 'ServiceProvider',
          Key: {
            "ProviderName": {
              "S": "Imgur"
            }
          }
        };

        dynamodb.getItem(params, function(err, data) {
          if (err) {
            console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
            callback(err);
          } else {
//this query succeeds
            console.log("Query succeeded. " + JSON.stringify(data, null, 2));
            callback(data);

          }
        });

      }

1 个答案:

答案 0 :(得分:0)

正如您在问题中所述,该调用是异步的,因此访问结果的唯一方法是回调。

var test = this.getImgurClientId(function (data) {
            return data.Item.ClientId.S; //useless as the callback is asynchronous and is called in getImgurClient methdo
        });
        console.log('test ' + test); //the asynchronous call has not finished yet and you cannot wait for it

这样:

var test = this.getImgurClientId(function (data) {
           data.Item.ClientId.S; //here is the only place where your datas are accessible
        });

为了更优雅地处理异步回调,您可以查看Promise API