我在从不同API调用加载多个节点时遇到问题。每个节点类型都可以正常工作,但是gatsby-node.js只允许设置一种类型,所以所有的CreateNode工作都应该一次完成。我不知道它是不是因为多异步调用或者其他什么原因而不能工作.
我尝试过许多不同的方法,下面是最新的实验,但都失败了。
const axios = require('axios');
const crypto = require('crypto');
exports.sourceNodes = async ({ actions }) => {
const { createNode } = actions;
const fetchUsers = () => axios.get('http://192.168.0.71/api/manager/users/user/', {
method: 'GET',
headers: {
'Authorization': 'Bearer XXXX',
},
}).then(res => {
const hUsers = Object.keys(res.data).map((row,i) => {
const userNode = {
id: res.data[row].id,
parent: null,
internal: {
type: 'HomeyUsers',
},
children: [],
email: res.data[row].email,
name: res.data[row].name,
properties: res.data[row].properties,
enabled: res.data[row].enabled,
verified: res.data[row].verified,
picture: res.data[row].avatar,
role: res.data[row].role,
present: res.data[row].present,
asleep: res.data[row].asleep,
inviteUrl: res.data[row].inviteURL,
inviteToken: res.data[row].inviteToken
};
const contentDigest = crypto
.createHash('md5')
.update(JSON.stringify(userNode))
.digest('hex');
userNode.internal.contentDigest = contentDigest;
createNode(userNode);
});
});
const fetchDevices = () => axios.get('http://192.168.0.71/api/manager/devices/device/',{
method: 'GET',
headers: {
'Authorization': 'Bearer XXXX',
},
}).then(res => {
//const res = await fetchDevices();
const hDevices = Object.keys(res.data).map((row,i) => {
const deviceNode = {
id: res.data[row].id,
parent: null,
internal: {
type: 'HomeyDevices',
},
children: [],
name: res.data[row].name,
zone: res.data[row].zone
};
const contentDigest = crypto
.createHash('md5')
.update(JSON.stringify(deviceNode))
.digest('hex');
deviceNode.internal.contentDigest = contentDigest;
createNode(deviceNode);
});
});
const fetchFlows = () => axios.get('http://192.168.0.71/api/manager/flow/flow/',{
method: 'GET',
headers: {
'Authorization': 'Bearer XXXX',
},
}).then(res => {
//const res = await fetchFlows();
const hFlows = Object.keys(res.data).map((row,i) => {
const flowNode = {
id: res.data[row].id,
parent: '__SOURCE__',
internal: {
type: 'HomeyFlows',
},
children: [],
name: res.data[row].name,
folder: res.data[row].folder,
enabled: res.data[row].enabled,
actions: res.data[row].actions,
};
const contentDigest = crypto
.createHash('md5')
.update(JSON.stringify(flowNode))
.digest('hex');
flowNode.internal.contentDigest = contentDigest;
createNode(flowNode);
});
});
return Promise.all([hUsers, hDevices, hFlows]);
}发布于 2019-02-19 15:24:40
您的代码定义了3个返回承诺的函数:
const fetchUsers = () => axios.get(...)
const fetchDevices = () => axios.get(...)
const fetchFlows = () => axios.get(...)但你哪儿也没给他们打电话。Promise.all期望得到一组承诺,但是您传入了三个未在相同范围内定义的变量
return Promise.all([hUsers, hDevices, hFlows]); 也许这会让你走得更远一些:
return Promise.all([fetchUsers(), fetchDevices(), fetchFlows()]);如果它仍然不起作用,那么第一件你应该分享的事情就是你的错误信息--它会对其他人有很大的帮助!盖茨比把很多东西扔到控制台里,所以你必须看着它看任何红色的,或看起来不寻常的东西。
https://stackoverflow.com/questions/54757209
复制相似问题