Amazon DynamoDB DocumentClient().get() 使用函数外的值
Amazon DynamoDB DocumentClient().get() use values outside of function
如何在 docClient.get()
之外获得 data.Item.Name
以进一步在其他功能中使用它。
const docClient = new awsSDK.DynamoDB.DocumentClient();
docClient.get(dynamoParams, function (err, data) {
if (err) {
console.error("failed", JSON.stringify(err, null, 2));
} else {
console.log("Successfully read data", JSON.stringify(data, null, 2));
console.log("data.Item.Name: " + data.Item.Name);
}
});
// how can i use "data.Item.Name" here:
console.log(data.Item.Name);
return handlerInput.responseBuilder
.speak(data.Item.Name)
.getResponse();
欢迎使用异步 javascript。
您的选择是:
- 在回调中继续你的逻辑
- 重构您的代码以使用 async/await
我将给出 async/await 选项的示例,但是您需要在代码的其他区域进行一些重构以支持此选项。
async function wrapper() {
const docClient = new awsSDK.DynamoDB.DocumentClient();
docClient = require('util').promisify(docClient)
var data = await docClient(dynamoParams);
console.log(data.Item.Name);
return handlerInput.responseBuilder
.speak(data.Item.Name)
.getResponse();
}
我假设您的代码位于一个名为 wrapper
的函数中。注意这个函数需要加上async
关键字
它现在也是 return 一个承诺,因此要从 wrapper
中获取 return 值,您需要 await
它(在您所在的代码部分'调用它)。这意味着您还需要将 async
关键字添加到顶级函数......等等。
如何在 docClient.get()
之外获得 data.Item.Name
以进一步在其他功能中使用它。
const docClient = new awsSDK.DynamoDB.DocumentClient();
docClient.get(dynamoParams, function (err, data) {
if (err) {
console.error("failed", JSON.stringify(err, null, 2));
} else {
console.log("Successfully read data", JSON.stringify(data, null, 2));
console.log("data.Item.Name: " + data.Item.Name);
}
});
// how can i use "data.Item.Name" here:
console.log(data.Item.Name);
return handlerInput.responseBuilder
.speak(data.Item.Name)
.getResponse();
欢迎使用异步 javascript。
您的选择是:
- 在回调中继续你的逻辑
- 重构您的代码以使用 async/await
我将给出 async/await 选项的示例,但是您需要在代码的其他区域进行一些重构以支持此选项。
async function wrapper() {
const docClient = new awsSDK.DynamoDB.DocumentClient();
docClient = require('util').promisify(docClient)
var data = await docClient(dynamoParams);
console.log(data.Item.Name);
return handlerInput.responseBuilder
.speak(data.Item.Name)
.getResponse();
}
我假设您的代码位于一个名为 wrapper
的函数中。注意这个函数需要加上async
关键字
它现在也是 return 一个承诺,因此要从 wrapper
中获取 return 值,您需要 await
它(在您所在的代码部分'调用它)。这意味着您还需要将 async
关键字添加到顶级函数......等等。