Coffeescript wait for multiple api calls to be over - rest

i am writing a coffeescript, where i am calling around 1000 http URL 's, parsing each and every data from each call and creating an array of result objects. Finally i need to access the array of objects and sort them.
Whats happening is, the code is not waiting for each and every call to be over and instead goes to end of the code where i am sorting the result array. Since the api calls are not over, the resulting array is null and hence getting an exception. I am pasting my code below. Please help me here
topChannels = []
calcMsgCount = (value) ->
channelhistoryURL = 'https://some-url'
msg.http(channelhistoryURL)
.header('Accept', 'application/json')
.get() (err, res, body) ->
if res.statusCode is 200
try
data = JSON.parse body
Channel =
id: data.id
name: data.name
messagecount: data.messages.length
topChannels.push(Channel)
value++
if (value < response.channels.length)
setTimeout calcMsgCount(value),1000
catch err
msg.send "JSON parsing error"
msg.send value
msg.send err
else
msg.send "error while retrieving channel history"
index=0;
calcMsgCount(index);
# Sorting topChannels array based on total number of messages
sortByMsgCount = (array, key) ->
array.sort((a,b) -> b[key] - a[key])
sortByMsgCount(topChannels, 'messagecount')

Related

tronweb : how to get return value using tronweb contract send function

let contract = await window.tronWeb.contract().at(config.contract);
let result = await contract.methods.depositTron()
.send({callValue:amount*1000000})
.then(output=>transaction = output);
console.log("result", result);
I tried to get the result of depositTron method, but returned hash value.
how should I do?
please help me.
Functions invoked by transactions only return value within the EVM (usually when called from another contract).
The hash returned from the send() JS function, is the transaction hash.
You can workaround this by emitting an event log within the contract. Then you can get the value or read emitted logs from the transaction receipt (emitted in JS after the transaction is mined).
Solidity:
contract MyContract {
event Deposit(uint256 indexed amount);
function depositTron() external payable {
emit Deposit(msg.value);
}
}
JS:
contract.methods.depositTron().send({callValue:amount*1000000})
.on('receipt', (receipt) => {
console.log(receipt.logs);
})

Postman if/else condition not working properly

This code is not working as expected when running collection and used as a test script on the first request:
when console.log gives output null, the collection doesn't stop, when it should.
function never goes to the 'else' condition, even when I force it by changing the GET results.
pm.test("Any?", function () {
var jsonData = pm.response.json();
if (pm.expect(jsonData.metadata.total_data).to.eql(0))
{console.log('null');
postman.setNextRequest(null);}
else
{console.log('Next request');
postman.setNextRequest('Name of Next request');}
});
Use a forEach and store the jsonData you want to check in a data array.
let checkingValues= [4,1,5,6,2];
checkingValues.forEach(() => {

actions on google--unable to use app.tell to give response from JSON

I am trying to get my webhook to return a parsed JSON response from an API. I can log it on the console, but when I try to use app.tell; it gives me: TypeError: Cannot read property 'tell' of undefined. I am basically able to successfully get the data from the API, but I'm not able to use it in a response for some reason. Thanks for the help!
[Actions.API_TRY] () {
var request = http.get(url2, function (response) {
// data is streamed in chunks from the server
// so we have to handle the "data" event
var buffer = "",
data,
route;
response.on("data", function (chunk) {
buffer += chunk;
});
response.on("end", function (err) {
// finished transferring data
// dump the raw data
console.log(buffer);
console.log("\n");
data = JSON.parse(buffer);
route = data.routes[0];
// extract the distance and time
console.log("Walking Distance: " + route.legs[0].distance.text);
console.log("Time: " + route.legs[0].duration.text);
this.app.tell(route.legs[0].distance.text);
});
});
}
This looks to me to be more of a JavaScript scoping issue than anything else. The error message is telling you that app is undefined. Often in Actions, you find code like yours embedded in a function which is defined inside the intent handler which is passed the instance of your Actions app (SDK or Dialog Flow).

return value from a jquery get callback function

It would be very useful to me if you could help me fix this function:
textParseQuery = (txtSnippet) ->
queryUrl = "http://localhost:8083/txtParse/#{txtSnippet}"
console.log queryUrl
callback = (response) =>
parsed = $.parseJSON response
companies = parsed.map (obj) -> new Company(obj.name, obj.addr)
companies
res = $.get queryUrl, {}, callback
console.log res
I would like to fetch the results from the callback so that the textParseQuery function could return a value.
The point of a callback is it's asynchronous, your response comes in the callback, so you need to handle the rest of the execution from the callback (e.g., the console.log res is going to execute before your callback is called, since it's part of the same synchronous execution of your ajax call).
textParseQuery = (txtSnippet) ->
queryUrl = "http://localhost:8083/txtParse/#{txtSnippet}"
callback = (response) ->
parsed = $.parseJSON response
companies = parsed.map (obj) -> new Company(obj.name, obj.addr)
# proceed from here
console.log companies
$.get queryUrl, {}, callback
Additional note: the fat arrow is unnecessary here, it's used to rebind what this refers to, but you aren't referencing this at all in your callback. If you're learning coffee, most editors will have plugin/modules to quickly compile coffee to JS, so use that to see what a given coffee syntax compiles to in JS (e.g., take a look at the diff between using -> and => when you compile your coffee)
I have discovered IcedCoffeeScript helps streamline the asynchronous control flow with await and defer. This is what I have tried to achieve. The code structure is how I pictured it
# Search for 'keyword' on twitter, then callback 'cb'
# with the results found.
search = (keyword, cb) ->
host = "http://search.twitter.com/"
url = "#{host}/search.json?q=#{keyword}&callback=?"
await $.getJSON url, defer json
cb json.results

Get a server method result before executing a Collection transform

Working on CoinsManager, I have a model directory with a class per file, and I want to read and list all those files in my collection transform method, to initialize my doc with the correct class.
server/methods.coffee:
Meteor.methods
implemented_coins: ->
"""
Returns a list of coins that have been implemented
"""
files = fs.readdirSync './app/models/cryptos/'
file.replace(".coffee.js", "") for file in files.filter (file) ->
file.search("(base_crypto*)|(js.map)") == -1
collections/addresses.coffee:
if Meteor.isReady
#implementedCoins = Meteor.call "implemented_coins"
#Addresses = new Meteor.Collection "addresses",
transform: (doc) ->
# Retrieve class from code, and pass it the address
if doc.code in #implementedCoins
new #[doc.code] doc.address
else doc
client/views/addresses/addresses_list.coffee
Template.userAddresses.helpers
userAddresses: ->
addresses = Addresses.find
userId: Meteor.user()._id
address.set_balance() for address in addresses
return addresses
Right now, I'm getting the following error on the client console:
Exception from Deps recompute: TypeError: Array.prototype.indexOf called on null or undefined
at indexOf (native)
at Addresses.Meteor.Collection.transform
Which means that in my collection transform, the #implementedCoins variable is undefined, because I didn't implement it correctly.
Any idea how to solve this problem ?
I'm pretty sure that this is wrong:
if Meteor.isReady
#implementedCoins = Meteor.call "implemented_coins"
I don't think there is a field in Meteor with that name, and even if it was, then it would get executed on startup, but at that time isReady is probably false and so your variable doesn't get set. Did you mean Meteor.startup? Secondly, on the client you need to use a callback for call, since there are no fibers on the client.
Would this work instead?
Meteor.startup(function () {
Meteor.call("implemented_coins", function(err, res) {
implementedCoins = res;
});
});