在 meteor 中使用 bluebird 库将数据从远程 API 保存到本地 mongo db
Using bluebird library in meteor to save data from remote API into local mongo db
Meteor.methods({
'sync.toggl'(apiToken) {
const toggl = new TogglApi({ apiToken });
Promise.promisifyAll(toggl);
toggl.getWorkspacesAsync()
.each(ws => toggl.getWorkspaceProjectsAsync(ws.id)
.map(p => {
Projects.upsert({ projectId: p.id }, {
projectId: p.id,
name: p.name,
tracker: 'toggl',
tags: [],
contributors: []
});
})
.catch(err => console.error(`fetching ${ws.name} projects error - ${err.message}`));
)
.catch(err => console.error(`fetching ${ws.name} workspace error - ${err.message}`));
}});
我正在尝试将数据从 toggl api 保存到本地数据库中。但是 Meteor 抛出错误 - Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
我找到了几个解决方案,但它们不允许我使用 bluebird promises ......还是不行?
使用 async/await
对我有用:
Meteor.methods({
'sync.toggl'(apiToken) {
const toggl = new TogglApi({ apiToken });
Promise.promisifyAll(toggl);
async function saveProject(pid, name) {
try {
return await Projects.upsert(
{ pid },
{
pid,
name,
tracker: 'toggl',
contributors: [],
}
)
} catch (err) {
return console.error(`async saveProject failed - ${err.message}`);
}
}
toggl.getWorkspacesAsync()
.each(ws => toggl.getWorkspaceProjectsAsync(ws.id)
.map(p => {
saveProject(p.id, p.name);
})
.catch(err => console.error(`fetching projects error - ${err.message}`))
)
.catch(err => console.error(`fetching workspaces error - ${err.message}`))
}});
Meteor.methods({
'sync.toggl'(apiToken) {
const toggl = new TogglApi({ apiToken });
Promise.promisifyAll(toggl);
toggl.getWorkspacesAsync()
.each(ws => toggl.getWorkspaceProjectsAsync(ws.id)
.map(p => {
Projects.upsert({ projectId: p.id }, {
projectId: p.id,
name: p.name,
tracker: 'toggl',
tags: [],
contributors: []
});
})
.catch(err => console.error(`fetching ${ws.name} projects error - ${err.message}`));
)
.catch(err => console.error(`fetching ${ws.name} workspace error - ${err.message}`));
}});
我正在尝试将数据从 toggl api 保存到本地数据库中。但是 Meteor 抛出错误 - Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.
我找到了几个解决方案,但它们不允许我使用 bluebird promises ......还是不行?
使用 async/await
对我有用:
Meteor.methods({
'sync.toggl'(apiToken) {
const toggl = new TogglApi({ apiToken });
Promise.promisifyAll(toggl);
async function saveProject(pid, name) {
try {
return await Projects.upsert(
{ pid },
{
pid,
name,
tracker: 'toggl',
contributors: [],
}
)
} catch (err) {
return console.error(`async saveProject failed - ${err.message}`);
}
}
toggl.getWorkspacesAsync()
.each(ws => toggl.getWorkspaceProjectsAsync(ws.id)
.map(p => {
saveProject(p.id, p.name);
})
.catch(err => console.error(`fetching projects error - ${err.message}`))
)
.catch(err => console.error(`fetching workspaces error - ${err.message}`))
}});