Export result outside the function
jankulik opened this issue · 6 comments
When I am making getContentReplies call, I can easily access results through result
variable inside the function.
steem.api.getContentReplies.author, permlink, function(err, result)
{
console.log(result);
});
However, when I am trying to export this result outside the function and assign it to some global variable it seems not to work. I have even tried to export it by localStorage
, but this also failed.
Anyone could help?
How you assign this values? And when you are trying to get them?
Probably you are trying to get this values before getting them. Your post suggests that method works properly.
var replies = new Array();
steem.api.getContentReplies(author, permlink, function(err, result)
{
replies = result;
console.log(replies);
});
console.log(replies);
The first console.log(replies)
(this one inside the function) works properly and returns a correct array of replies. The second one returns an empty array.
So everything works properly :-)
I will explain what your program does:
- Create empty array.
- Call steem api for post replies AND (important) after you receive answer assign it to array and print it.
- Just after calling api (so most probably before getting response) print to console array value.
So second console log prints empty array, because api call is asynchroneus function
Did i help you? :-)
Thank you very much @BartolomeoItaliano, everything is clear now :)
However, what is the best method to get the result from the asynchronous function? I tried with promises, await, then etc. but always failed. I am unfortunately not very familiar with js, could you give me some hint?
Await works only with promises. Its a not nested way of resoving them. So it won't work with method where result is returned in callback. As you are new to js, first you can just nest functions in functions :)
You have this result in callback exactly, whatever you want to do with this result do by calling another method in calback.
Thank you for your help @BartolomeoItaliano :) I think my problem is solved.