簡體   English   中英

在 Next.js 中,序列化 getStaticProps 時出錯?

[英]In Next.js, Error serializing getStaticProps?

我的 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 源代碼

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

    return { props: { posts } }
}

posts.js 源代碼

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

通過分配Promise.all的結果並將其傳遞,我能夠解決 promise 鏈。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM