在 Next.js 中,序列化 getStaticProps 时出错?

时间:2021-03-25 16:53:08

标签: javascript promise next.js

我的 Next.js 应用程序出现以下错误:

Error: Error serializing `.posts[0]` returned from `getStaticProps` in "/blog". Reason: `object` ("[object Promise]") cannot be serialized as JSON. Please only return JSON serializable data types.

我知道在某处解决我的承诺一定有问题,但我迷路了。请帮忙!

index.js source code

export async function getStaticProps() {
    const posts = await getSortedPosts()

    return { props: { posts } }
}

posts.js source code

export async function getSortedPosts() {
    const fileNames = readdirSync(POSTS_DIR)
    const allPostsData = fileNames.map(fileName => {
        const slug = fileName.replace(/\.md$/, '')
        return getPost(slug)
    });
    await Promise.all(allPostsData);

    return allPostsData.sort((a, b) => (a.date < b.date ? 1 : -1))
}

export async function getPost(slug) {
    const fullPath = path.join(POSTS_DIR, `${slug}.md`)
    const fileContents = readFileSync(fullPath, 'utf8')

    const { content, data: meta } = parseYaml(fileContents)
    const contentHtml = await markdownToHtml(content)

    return {
        slug,
        contentHtml,
        ...meta,
    }
}

async function markdownToHtml(md) {
    const processedContent = await remark()
        .use(remarkHtml)
        .process(md)

    return processedContent.toString()
}

1 个答案:

答案 0 :(得分:0)

我能够通过分配 Promise.all 的结果并将其传递来解析承诺链。

const promises = fileNames.splice(0, 2).map(fileName => {
        const slug = fileName.replace(/\.md$/, '')
        return getPost(slug)
    });
    const allPostsData = await Promise.all(promises); // Assign result of promise chain