3 Replies - 715 Views - Last Post: 27 December 2012 - 02:58 AM

#1 for3v3rforgott3n  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 77
  • Joined: 17-June 09

Trying to call API function in JS

Posted 25 December 2012 - 03:23 PM

Hi guys,

I'm having problems calling this API:

var api = (function() {

	function randResponseFn(data, maxWaitSecs) {
		return function(callback) {
			var waitTime = maxWaitSecs * Math.random();
			setTimeout(function() {
				callback(data);
			}, waitSecs);
		}
	}

	return {
		getUserInfo: randResponseFn({name: "Bobby Tables", id: 1}, 5 * 1000),

		getUserFriends: randResponseFn([{name: "Inactive User", id:2}, {name: "Test User", id:3}],2 * 1000)		
	}
	
})();



So far I have this:

window.onload = function() {

    var testObj = {
	name: 'Testing This'
    }
    
    var output = api.getUserInfo(testObj);
    alert(output);
}




But this error shows up in console: Uncaught ReferenceError: waitSecs is not defined


Any ideas?

Is This A Good Question/Topic? 0
  • +

Replies To: Trying to call API function in JS

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4316
  • View blog
  • Posts: 12,096
  • Joined: 18-April 07

Re: Trying to call API function in JS

Posted 25 December 2012 - 04:18 PM

Well that is because the variable is called "waitTime" not "waitSecs" in your setTimeout() function call.

var waitTime = maxWaitSecs * Math.random();

setTimeout(function() {
   callback(data);
}, waitSecs);  //<-- waitTime variable defined above? 



You don't have a variable called waitSecs created. :)
Was This Post Helpful? 0
  • +
  • -

#3 for3v3rforgott3n  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 77
  • Joined: 17-June 09

Re: Trying to call API function in JS

Posted 25 December 2012 - 05:14 PM

Oh silly me, thanks!

The function requires a callback, and it returns an object but I'm not sure how to store that.

Right now I have

api.getUserInfo(function() {
	//How do I store the returned object here?
});



And are there any resources I can take a look at along these lines?

This post has been edited by for3v3rforgott3n: 25 December 2012 - 05:15 PM

Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3485
  • View blog
  • Posts: 10,045
  • Joined: 08-June 10

Re: Trying to call API function in JS

Posted 27 December 2012 - 02:58 AM

View Postfor3v3rforgott3n, on 26 December 2012 - 01:14 AM, said:

The function requires a callback, and it returns an object but I'm not sure how to store that.

I don’t see where an object is returned. api.getUserInfo() is a function with some closures. there’s no return statement anywhere.

function(callback) {
	var waitTime = maxWaitSecs * Math.random();
	setTimeout(function() {
		callback(data);
	}, waitSecs);
}



PS. API here refers to the Module Pattern.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1