10

I'm pretty new to JavaScript and node.js and so being thrown into Promises is pretty daunting when it is required for my bot to function.

var storedUserID; ROBLOX.getIdFromUsername(accountArg).then(function(userID) { message.reply("your id is " + userID); storedUserID = userID; }); message.reply(storedUserID); 

This is essentially what I have written out, it creates a variable called 'storedUserID' which I would like to update later. I am trying to update it in the Promise but it does not seem to work.

In the code, there is message.reply("your id is " + userID); which works as expected. It will print out to a user 'your id is [NUMBER]' so I know userID is not null.

However, when I run message.reply(storedUserID); outside of the Promise, nothing is printed as the variable is not saved. I am not sure why.

Any help would be appreciated as this is going towards my work in college! Thank you!

2
  • The then is run asynchronously. By the time you log that callback hasn't executed yet. Commented Nov 4, 2017 at 16:04
  • @IngoBürk See OP at "which I would like to update later." How does linked Question and answers demonstrate how to change the value of a Promise? Commented Nov 4, 2017 at 16:20

2 Answers 2

13

return the value at function passed to .then()

var storedUserID = ROBLOX.getIdFromUsername(accountArg) .then(function(userID) { return userID; }); 

you can then use or change the Promise value when necessary

storedUserID = storedUserID.then(id) { return /* change value of Promise `storedUserID` here */ }); 

access and pass the value to message.reply() within .then()

storedUserID.then(function(id) { message.reply(id); }); 

or

var storedUserID = ROBLOX.getIdFromUsername(accountArg); // later in code storedUserID.then(function(id) { message.reply(id); }); 
Sign up to request clarification or add additional context in comments.

6 Comments

What's the point of mapping the promise to itself?
@IngoBürk Do you mean the second example at updated post?
Yes. But my question stands: why is that the second alternative? What's the point of the first one?
@IngoBürk To demonstrate that the value of a Promise can be changed at .then() by returning a different value, see OP at "which I would like to update later."
Ah, I see what's going on.. thanks! Still kinda confused with this whole asynchronous thing. :]
|
0

Because the getIdFromUsername is asynchronous, the final line where you message.reply the stored ID is run before the ID is stored.

Asynchronous functions like getIdFromUsername don't stop the following lines of code from running. If you want it to happen after the ID is returned it needs to go inside the then callback.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.