无法将字符串推入数组

Unable to push string into array

我正在尝试学习 EJS 并制作博客,但我似乎无法理解这个错误

我想做的是尝试将一些数据库响应作为对象写入数组,然后将其推送到文件。 我正在使用 replit DB

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 class="media content-section">
        <div class="media-body">
          <div class="article-metadata">
            <a class="mr-2" href="/p">Anonymous</a>
            <small class="text-muted">${db.get(key).date_posted}</small>
          </div>
          <h2><a class="article-title" href="#">${ db.get(key).title }</a></h2>
          <p class="article-content">${ db.get(key).content }</p>
        </div>
      </article`
      )
    })
  });

  posts = posts.join()

  fs.writeFileSync("public/posts.ejs", posts)
}

我在 运行 代码时遇到的错误:

UnhandledPromiseRejectionWarning: TypeError: posts.push is not a function

首先,您声明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 class="media content-section">
      <div class="media-body">
        <div class="article-metadata">
          <a class="mr-2" href="/p">Anonymous</a>
          <small class="text-muted">${db.get(key).date_posted}</small>
        </div>
        <h2><a class="article-title" href="#">${ db.get(key).title }</a></h2>
        <p class="article-content">${ 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 class="media content-section">....</article`).join();

  fs.writeFileSync("public/posts.ejs", posts)
}