gpt4 book ai didi

Node.js:如何使异步数据全局可用

转载 作者:太空宇宙 更新时间:2023-11-03 23:01:57 25 4
gpt4 key购买 nike

我是 Node.js 新手。我正在使用 DynamoDB local 从数据库读取数据,如下所示。

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);
}
});

据我了解,这是一个异步函数,无法返回。异步数据仅在函数成功事件内可用。

但是我需要使结果数据在函数外部可用,因为我需要将其返回到html。我该怎么做?

最佳答案

对于你的情况,我建议使用 promise 。这是您的代码。

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');
});

关于Node.js:如何使异步数据全局可用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45625204/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com