我正在嘗試學習 EJS 并制作博客,但我似乎無法理解此錯誤
我想要做的是嘗試將一些 db 回應作為物件寫入陣列,然后將其推送到檔案。我正在使用 replit 資料庫
const fs = require("fs")
const Database = require("@replit/database")
const db = new Database()
exports.load = async function(){
db.set("hello", {
"author": "Some author 1",
"title": "Blog Post 1",
"content": "First post content",
"date_posted": "Dec 17, 2021"
})
var posts = new Array()
db.list().then(keys => {
keys.forEach(key => {
posts.push(` <article >
<div >
<div >
<a href="/p">Anonymous</a>
<small >${db.get(key).date_posted}</small>
</div>
<h2><a href="#">${ db.get(key).title }</a></h2>
<p >${ db.get(key).content }</p>
</div>
</article`
)
})
});
posts = posts.join()
fs.writeFileSync("public/posts.ejs", posts)
}
運行代碼時遇到的錯誤:
UnhandledPromiseRejectionWarning: TypeError: posts.push is not a function
uj5u.com熱心網友回復:
首先,您宣告var posts = new Array(). posts陣列也是如此。下一行(在執行順序): posts = posts.join()。所以現在posts是一個空字串。您正在更改變數的型別,這是一種不好的做法(Typescript 不允許您這樣做)。在執行順序現在下一行:.then(keys =>。你開始把東西推入posts,但posts現在是一個字串,記得嗎?不再是陣列了。
您async無緣無故地使用關鍵字,因為其中沒有await。你不妨利用它:
exports.load = async function(){
db.set("hello", {
"author": "Some author 1",
"title": "Blog Post 1",
"content": "First post content",
"date_posted": "Dec 17, 2021"
})
let postsArray = new Array();
const keys = await db.list();
keys.forEach(key => {
postsArray.push(`<article >
<div >
<div >
<a href="/p">Anonymous</a>
<small >${db.get(key).date_posted}</small>
</div>
<h2><a href="#">${ db.get(key).title }</a></h2>
<p >${ db.get(key).content }</p>
</div>
</article`
)
})
const posts = postsArray.join()
fs.writeFileSync("public/posts.ejs", posts)
}
或在一行中使用 .map() :
exports.load = async function(){
db.set("hello", {
"author": "Some author 1",
"title": "Blog Post 1",
"content": "First post content",
"date_posted": "Dec 17, 2021"
})
const keys = await db.list();
const posts = keys.map( key => `<article >....</article`).join();
fs.writeFileSync("public/posts.ejs", posts)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/399081.html
標籤:javascript 节点.js 数组 ejs
