Node.js GraphQL发送了正确的数据,但变量未定义
希望我没有忽略一些愚蠢的事情,但问题是 我正在使用promise获取此Smartsheet数据:Node.js GraphQL发送了正确的数据,但变量未定义,node.js,graphql,Node.js,Graphql,希望我没有忽略一些愚蠢的事情,但问题是 我正在使用promise获取此Smartsheet数据: var getWorkspaces = async function(args) { var smartsheet = client.createClient({ accessToken: "key" }); await smartsheet.workspaces.listWorkspaces() .then(async function(workspaceList) {
var getWorkspaces = async function(args) {
var smartsheet = client.createClient({ accessToken: "key" });
await smartsheet.workspaces.listWorkspaces()
.then(async function(workspaceList) {
var data = await workspaceList.data;
console.log("returning");
console.log(data);
return data;
})
.catch(function(error) {
console.log(error);
});
}
这是我的解析器
:
var resolvers = {
Query: {
workspaces: async () => {
var workspaceData = await getWorkspaces();
console.log("sending");
console.log(workspaceData);
return workspaceData;
}
}
};
为什么这是控制台输出:
returning
[
{
id: 000,
name: 'nname',
accessLevel: 'ADMIN',
permalink: 'link'
},
{
id: 000,
name: 'name',
accessLevel: 'ADMIN',
permalink: 'link'
},
{
id: 000,
name: 'name',
accessLevel: 'ADMIN',
permalink: 'link'
}
]
sending
undefined
更具体地说,为什么
工作空间列表未定义?我已经做了几个小时了,找不到解决方案。这里的问题是,您的返回工作空间数据
在.then()
的回调函数中,因此您是在回调中返回,而不是在getworkspace()
函数中返回。当您说.next()
时,请求以异步方式发生。使用wait
时,当前线程将等待响应并执行它,而不需要回调–同步调用wait
隐式调用.next()
,添加try
/catch
相当于.catch()
var getWorkspaces = async function(args) {
try {
var smartsheet = client.createClient({ accessToken: "key" });
var workspaceList = await smartsheet.workspaces.listWorkspaces();
var data = workspaceList.data;
console.log("returning");
return data;
} catch (err) {
console.log(err);
}
}