我正在尝试将一组字符串从数据库带到我创建的网站上的下拉菜单中。除了数据从检索方法到网站的最终传输之外,我的一切都正常工作。现在数据是 Promise 的形式,我一辈子都想不出如何把它打印在我的网页上。现在我只是将它发送到 localhost:3000,我还没到将它放入下拉列表的地步。我该怎么做?
我在网上发现的关于这个问题的信息非常少,因此主要只是尝试一些没有真正起作用的黑客修复(解决 resolve() 方法、all() 方法)。两者都导致语法错误。顺便说一句,所有 Var 名称/SQL 查询都已更改。我最近的尝试如下:
//code that sends the names to the webpage
app.get('/formfetch', function(req, res) {
const data = async() => {
let rawDat = await dbFormFetch.getNames();
return rawDat;
}
}
const hNs = data();
hNs.then((names) => {
if (names === null) {
res.end("Error: Names list came through as null.");
} else if (names.length > 0) {
resolve(names);
for (var i = 0; i < names.length; i++) {
res.end(names[i]);
}
res.status('200');
}
})
.catch((err) => {
res.status('404').json(err)
console.log("conversion of promise failed")
})
});
//the getNames() method (in a different file)
async function getNames() {
console.log("trying to get Names");
let query = `select NAME from NAMESTAB`;
console.log("query: " + query);
const binds = {};
const result = await database.simpleExecute(query, binds);
var results = [];
console.log("for loop in formfetch.js: ");
for (var i = 0; i < result.rows.length; i++) {
results[i] = i + ": " + result.rows[i].NAME+ ' \n';
}
return results;
}
app.get 函数中的 res.send 方法在我的本地主机上打印出“Made it to the Web server:”。我检查了控制台,没有看到任何隐藏在 html 或类似内容中的东西。
**注意:promise 中应该包含的所有数据都在代码中(我可以在代码中的任何位置将其打印到控制台),但是当我将其放在网站上时,它不会打印。 **
最佳答案
这里有这么大的惊喜,我做错了。今日类(class):在运行和编写一些异步代码之前阅读 Promise 及其工作原理。它不像您希望的那样直观。
// I only had made changes to the first of the two methods.
app.get('/formfetch', function(req, res) {
async function data() {
let rawDat = await dbFormFetch.getNames();
return rawDat;
}
data().then((Names) => {
if (Names === undefined) {
res.end("Error: Names list came through as null.");
} else if (Names.length > 0) {
res.setHeader('Content-Type', 'application/json');
res.status(200).json({ "names": Names });
}
})
.catch((err) => {
res.status('404').send("name retrieval failed in server.js module")
console.log(err)
console.log("conversion of promise failed")
})
});
当您使用 res.end()
时, 它会设置 header 状态并在调用此方法后使其不可变,因此使用是错误的。而不是这个,我使用了 setHeader()
方法告诉网站我要发送什么样的信息,然后通过链接 .json()
填写内容。 status()
的方法我发送的回复。我以前从未使用过 promises,而且我对 NodeJS 还很陌生,所以这是一个学习曲线,但希望这能帮助那些我昨天还在的人。如果您不熟悉 promise ,请参阅 this article和 this article在您尝试使用此编码工具之前。您将节省数小时的调试和错误跟踪时间。
关于javascript - 如何将 promise 的数据打印到网页?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56839721/