autoValue fails to return a value


#1

Hello guys, so I’m working on an application where users submit a url and receive a shortened version of it. Now as you can see in the image below, when a user sumbits a url, I’m supposed to receive the normal one and the encoded one too, but I only get the normal one and absolutely no errors in the database. How come?!

meteor

import SimpleSchema from 'simpl-schema';
import { Tracker } from 'meteor/tracker';

// Required AutoForm setup
SimpleSchema.extendOptions(['autoform']);
SimpleSchema.debug = true;

Links = new Mongo.Collection("links");

LinksSchema = new SimpleSchema({
  url: {
    type: String,
    label: 'Input',
    regEx: SimpleSchema.RegEx.Url,
    index: true,
    unique: true,
     autoform: {
      afFieldInput: {
      type: "url",
      placeholder: "Place your links here...",
    }
    }
  },
  encodedUrl: {
      type: String,
      optional: true,
      autoValue: function() {
        var url = this.field("url");
        
       if (url.isSet) {
       return Meteor.call("shortenUrl", url.value, function(error, result){ if(error){ console.log(error); }else{ return result; } });
       } else {
           this.unset();
       }
        }
  } 
   
}, { tracker: Tracker });

Links.attachSchema(LinksSchema);

#2

The issue you are having is due to Meteor.call running asynchronously. If you remove the callback then it will run synchronously on the server and work properly. On the client it will just return undefined but that shouldn’t matter as it will get a value once it hits the server.


#3

I made it synchronous but now the whole thing wouldn’t work in the first place and I get this in the console:meteor2

 return Meteor.call("shortenUrl", url.value);

#4

What is the error that it’s displaying on the server?


#5

Oh, sorry mate, I forgot to define the access token as I’m using google url shortening service, my bad.
On a side note, why is it such a bad thing to use asynchronous call within my schema?


#6

An async call will not block execution and will allow the current execution context to complete and return before the async call completes and therefore cannot return a value to that execution context.


#7

So generally speaking, it’s not advised to do any asynchronous calls on server side, correct?
Thank you so much for helping me dude, I appreciate it!


#8

I wouldn’t say that it’s not advised. You do however need to understand how to handle the asynchronicity. In general Meteor provides ways to run most of it’s API that might be async in an pseudo-synchronous manor. Most other libraries are moving to promises that you can use instead of call backs and in this case with Meteor you can use ES7’s async/await with them.


#9

Well I’d rather stay away since I’m a novice and I don’t want to complicate things for me. Have a nice day!