Request serverside and insert to db

Hello!

I’ve been trying a couple of hours to make this work, but i just cant figure it out.
I’m fetching some json data with request, looping through it and trying to insert into the db.
I’ve removed a bunch of code to make it cleaner for you. Don’t worry about that!

Error:

Meteor code must always run within a Fiber. Try wrapping callbacks that you pass to non-Meteor libraries with Meteor.bindEnvironment.

I’ve tried to implement Meteor.bindEnvironment, Meteor.wrapAsync & Fibers.

But i’m doing something wrong, can someone help me out here? :slight_smile:

main.js

import { Meteor } from 'meteor/meteor'
import '../imports/api/games.js'
import { Games } from '../imports/api/games.js'

const request = require('request-promise')

request(url).then(res => {
  res = JSON.parse(res)
  for(i in res){
    const game = res[i]
    Games.insert({
      name: game.name,
      date: new Date()
    })
  }
})

Meteor.startup(() => {
  
})

request-promise uses Bluebird for its Promises. Bluebird Promises don’t play well with Fibers.

I explain how to get this working in this article. In a nutshell you could:

  • Use the rawCollection().insert method, or
  • import { Promise } from 'meteor/promise'; and make use of Promise.await(), or
  • Modify your code to use async/await, in which case the Bluebird Promise will be resolved by Meteor’s Promise library.

I looked through your guide before posting this thread, even though the title sounds perfect “Using Promises and async/await in Meteor”. It didn’t help me. Perhaps i’ll have to give it more time. This is the fifth time i’m rage-quitting meteor because so many simple things like this just turns out to be so hard.

I made a simple test

import { Meteor } from 'meteor/meteor'
import { Promise } from 'meteor/promise'

const request = require('request')

const callback = (err, res, body) => {
  console.log(body)
}

Promise.await(request('http://google.com', callback))

After ‘meteor add promise’ and running, i get
Error: Cannot find module ‘./lib/cookies’
/node_modules/fibers/future.js:280

Can you give me a super simple example where this is working? Otherwise ill just stick to plain node/express/mongoose

Thank you for your time and effort

Promises don’t take callbacks, so I’d do your example like this:

import { Meteor } from 'meteor/meteor'
import { Promise } from 'meteor/promise'

const request = require('request')

const result = Promise.await(request('http://google.com'))
console.log(result);
1 Like

Thank you for your response. I will read much more into this, i lack much knowledge.
Have a nice evening

1 Like