承诺和决心不起作用


const { GraphQLServer } = require('graphql-yoga');
const mongoose = require('mongoose');
mongoose.connect("mongodb://localhost/test1");
const Todo = mongoose.model('Todo',{
text: String,
complete: Boolean
});

const typeDefs = `
type Query {
hello(name: String): String!
}
type Todo{
id: ID!
text: String!
complete: Boolean!
}
type Mutation{
createTodo(text:String!): Todo
}
`
const resolvers = {
Query: {
hello: (_, { name }) => `Hello ${name || 'World'}`,
},
Mutation:{
createTodo: async (_,{ text }) => {
const todo = new Todo({text, complete: false});
await todo.save();
return todo;
}
}
};
const server = new GraphQLServer({ typeDefs, resolvers })
mongoose.connection.once("open", function() {
server.start(() => console.log('Server is running on localhost:4000'))
});

你好,我是节点js和mongoDB的新手。我正在尝试启动我的服务器,但它没有启动。每次显示如下错误时:

(node:17896) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 
This error originated either by throwing
inside of an async function without a catch block, or by rejecting a promise 
which was not handled with .catch(). (rejection id: 1)
(node:17896) [DEP0018] DeprecationWarning: Unhandled promise rejections are 
deprecated. In the future, promise rejections that are not handled will 
terminate the Node.js process with a non-zero exit code.

每次这都显示出一些承诺错误。任何人都可以帮我调试这个程序。我是初学者。我不太了解。但根据我的理解,我只写了正确的代码。

可能是你的保存函数抛出了一个你不处理的箭头! 您可以使用以下方法之一解决此问题:

GraphQL 自行处理 promise,所以这会给你相同的结果:

createTodo: (_,{ text }) => {
const todo = new Todo({text, complete: false});
return todo.save();
}

使用try catch可以更好地处理错误:

createTodo: async (_,{ text }) => {
const todo = new Todo({text, complete: false});
try {
await todo.save();
return todo;
} catch(err) {
\ do something with error
console.error('error=>', err);
return null;
}
}

最新更新