I have a list of email addresses, I looping through them and checking if they exist. If they don’t, then I create them on the server, but then in the same function I need to create a document and set a field as the created user’s ID. How can I accomplish this?
Accounts.createUser only returns the _id on the server, so on the client it’s undefined. I can use a callback, but the rest will have moved on using ‘undefined’, which doesn’t help anything.
Is this a job for promises? Futures? I honestly don’t really know what those are, but that they help with asynchronous functions, which I think is part of the issue here, right?
Because this function is run infrequently, it would even be OK if the whole script stopped and waited for the _id to return from the server, as it’s unlikely many new users will be created.
These are solutions I’ve looked at, which don’t work because I want to get the _id in the same function, and not accomplish some separate functionality when a new user is created:
I think I have something similar, unless I’m missing something… The problem is that Accounts.createUser only returns the user _id on the server, and I need to use it to create a document on both the client (minimongo) and server. I’ll give it a try later and see if it works.
OK @nxcong , I tried your code, the find on the users collection returns ‘undefined’ on the client (works on server), the userId is stored as ‘null’ in the new document.
I ended up installing grigio:babel, okgrow:promise, an .es6.js file, and using the async/await pattern to wait for the server to respond (example here: okgrow-promise.meteor.com/#example-three). It’s certainly easy, but I wonder if it would be better to make two scripts, set temporary user ID’s, then overwrite them with real values in a second pass over; it certainly seems more traditional.