重构gatsby-node.js承诺



我正在进行一个矿山项目,该项目是从盖茨比网站的免费模板开始的。我想在里面创建一个博客部分,没有什么太复杂的,所以我试着复制已经存在的内容,但它没有像我想的那样起作用,我正在为三个不同的页面创建三种不同的上下文,这有点难以理解,事实上,博客的索引页面有时会显示错误的查询。我很确定我不是Javascript承诺的大师,有人能帮忙吗?如果你这样做,我会非常感激,看看这个代码

const path = require(`path`);
const { createFilePath } = require(`gatsby-source-filesystem`);
exports.createPages = ({ graphql, actions }) => {
const { createPage } = actions;
return new Promise((resolve, reject) => {
graphql(`
{
allDatoCmsWork {
edges {
node {
slug
}
}
}
allDatoCmsBlog {
edges {
node {
slug
article
title
date
category
}
}
}
}
`).then((result) => {
result.data.allDatoCmsWork.edges.map(({ node: work }) => {
createPage({
path: `works/${work.slug}`,
component: path.resolve(`./src/templates/work.js`),
context: {
slug: work.slug,
},
});
});
result.data.allDatoCmsBlog.edges.map(({ node }) => {
createPage({
path: `blog/${node.slug}`,
component: path.resolve(`./src/templates/article.js`),
context: {
slug: node.slug,
},
});
createPage({
path: `blog/${node.category}`,
component: path.resolve(`./src/templates/gather-category.js`),
context: {
category: node.category
}
});
});
resolve();
});
});

};












尝试:

exports.createPages = async ({ graphql, actions }) => {
const result = await graphql(`
{
allDatoCmsWork {
edges {
node {
slug
}
}
}
allDatoCmsBlog {
edges {
node {
slug
article
title
date
category
}
}
}
}
`)
.then((result) => {
result.data.allDatoCmsWork.edges.map(({ node: work }) => {
createPage({
path: `works/${work.slug}`,
component: path.resolve(`./src/templates/work.js`),
context: {
slug: work.slug,
},
});
});
result.data.allDatoCmsBlog.edges.map(({ node }) => {
createPage({
path: `blog/${node.slug}`,
component: path.resolve(`./src/templates/article.js`),
context: {
slug: node.slug,
},
});
createPage({
path: `blog/${node.category}`,
component: path.resolve(`./src/templates/gather-category.js`),
context: {
category: node.category
}
});
});
});
};

注意asyncawait函数的基于promise的方法,因为graphql函数调用返回promise。请参阅:MDN文档更多信息。

相关内容

  • 没有找到相关文章

最新更新