Problems using promiseToFuture with an object coming from context.callmethod () - javascript

As the title suggests, I am trying to use promiseToFuture (function of the dart library dart:js_util) on an object deriving from the method of DART:JS which is context.callmethod (''), whose objective is to perform a JavaScript function, which identifies through the string passed as a parameter; The code below:
void onWalletConnect() {
var promiseWallet =
await promiseToFuture(js.context.callMethod('JsConnectWallet'));
// ignore: avoid_print
print(promiseWallet);
if (promiseWallet['address'].compareTo('errorAddress') != 0) {
setState(() {
walletAddress = promiseWallet['address'];
isWalletconnect = true;
});
}
}
// "`js.context.callMethod('..')` Returns an Object Promise; "
Below the import:
import 'dart:js' as js;
import 'dart:js_util';
To the execution of promisetofutures() [and I am sure that this is the function that generates error and not the js.context.callMethod()] I get the following error from the Chrome console:
"
Uncaught (in promise) TypeError: js.Promise.then in not a function
at Object.promiseToFuture (js_util.dart:275:35)
at _first._MyHomePageState.new.OnWalletConnect (_first.dart:28:1)
"
I don't understand why you generate this error and how to solve it, can anyone help me?

Related

Using Meteor.wrapAsync correctly

Hopefully this is a newbie question.
I have the following code that I am trying to convert to using meteor.wrapAsync. I am getting a "Exception while invoking method 'emailSend' ReferenceError: syncfunc is not defined" exception. What am i missing?
Stack Trace:
I20191031-06:21:16.246(-5)? Exception while invoking method 'emailSend' ReferenceError: syncfunc is not defined
I20191031-06:21:16.248(-5)? at MethodInvocation.emailSend (src/imports/api/email.js:13:27)
I20191031-06:21:16.249(-5)? at maybeAuditArgumentChecks (packages/ddp-server/livedata_server.js:1771:12)
I20191031-06:21:16.273(-5)? at DDP._CurrentMethodInvocation.withValue (packages/ddp-server/livedata_server.js:719:19)
I20191031-06:21:16.275(-5)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1234:12)
I20191031-06:21:16.276(-5)? at DDPServer._CurrentWriteFence.withValue (packages/ddp-server/livedata_server.js:717:46)
I20191031-06:21:16.277(-5)? at Meteor.EnvironmentVariable.EVp.withValue (packages\meteor.js:1234:12)
I20191031-06:21:16.277(-5)? at Promise (packages/ddp-server/livedata_server.js:715:46)
I20191031-06:21:16.278(-5)? at new Promise (<anonymous>)
I20191031-06:21:16.279(-5)? at Session.method (packages/ddp-server/livedata_server.js:689:23)
I20191031-06:21:16.280(-5)? at packages/ddp-server/livedata_server.js:559:43
email.js:
Meteor.methods(
{
emailSend(fromAddress, subject, emailText)
{
if (Meteor.isServer)
{
const { Email } = require('../server/email.js');
var syncFunc = Meteor.wrapAsync(Email.send);
var sendEmailReturn=syncfunc(fromAddress, subject, emailText);
return sendEmailReturn;
**//if I comment out the above three lines and uncomment the line below then the application works fine.**
//return Email.send(fromAddress, subject, emailText);
}
},
})
You don't need to use external callback to sync methods as Meteor supports "async" and "awaits" by default. Below is an example of using 'await' method.
Meteor.methods({
async emailSend(fromAddress, subject, emailText) {
const { Email } = require('../server/email.js');
var sendEmailReturn = await Email.send(fromAddress, subject, emailText);
}
});
I believe Meteor.defer is more suited to what you're trying to achieve here.
Example:
Meteor.methods({
'action_plus_email': function () {
// do something
Meteor.defer(() => {
Email.send(...)
})
return 'hello there, user';
}
})
https://www.meteor-tuts.com/chapters/1/meteorsnacks#Meteor-defer
https://apiko.com/blog/organization-of-email-sending-in-meteorjs/
And if you're are going to be sending many emails, please take a look at mail-time. It can be of great help.
https://github.com/VeliovGroup/Mail-Time

Calling Firebase Function from Unity throws error

I am having problems with my Unity3D calling Firebase Functions function. My code is actually copied from https://firebase.google.com/docs/functions/callable.
My function code is following: (just copied this file actually)
https://github.com/firebase/quickstart-js/blob/a579893cfa33121952aeed9069c1554ed4e65b7e/functions/functions/index.js#L44-L50
and in Unity I have this:
//Create the arguments to the callable function.
var data = new Dictionary<string, object>();
data["text"] = "message";
data["push"] = true;
//Call the function and extract the operation from the result.
var function = FirebaseFunctions.DefaultInstance.GetHttpsCallable("addMessage");
function.CallAsync(data).ContinueWith((task) => {
if (task.IsFaulted)
{
foreach (var inner in task.Exception.InnerExceptions)
{
if (inner is FunctionsException)
{
Debug.Log(inner.Message);
}
}
}
else
{
Debug.Log("Finished: " + task.Result.Data);
}
});
But I am getting this result:
Response is not valid JSON object.
What am I doing wrong?
Thank you for your help!!!
I was still working on that problem and suddenly it worked. I dont know why to be honest, because the could looks exactely the same and I did not change anything on that.

Javascript - cannot pass classes's function return into classes's variable

I program usually in python and I am trying something that usually works in python. I have a function in a class. Its a callback function of mqtt library. What I want is to save the message(in a function onMessageArrived) that I receive into class variable called (this.)buffer.
class sub{
constructor(hostname,port,clientid,topic){
this.buffer = [];
this.hostname=hostname;
this.port=port;
this.clientid = clientid;
this.topic = topic;
this.client = new Paho.MQTT.Client(hostname,port, clientid);
// set callback handlers
this.client.onConnectionLost = this.onConnectionLost;
this.client.onMessageArrived = this.onMessageArrived; <----Problem
// connect the client
this.client.connect({onSuccess:this.onConnect});
}
onConnect(){
console.log('OnConnect');
}
onConnectionLost(responseObject) {
if (responseObject.errorCode !== 0) {
console.log("onConnectionLost:"+responseObject.errorMessage);
}
}
onMessageArrived(message) {
console.log("onMessageArrived:"+message.payloadString);
this.buffer.push(message.payloadString) <-------------Problem
}
subs(){
this.client.subscribe(this.topic)
}
publ(message){
var mg = new Paho.MQTT.Message(message);
mg.destinationName = this.topic;
this.client.send(mg);
}
}
Problem is that function onMessageArrived doesnt push message into this.buffer variable-it looks like the function has no idea its inside class and therefore I cannot access class variable through 'this.'. In python it works this way. I am quite desperate because I looks to me like that function is totaly isolated and there is no other way than just print the message.
the error:
onConnectionLost:AMQJS0005E Internal error. Error Message: Cannot read
property 'push' of undefined, Stack trace: TypeError: Cannot read property
'push' of undefined
Thanks in advance

Build version information in Application Insights telemetry (client-side)

We have a SPA hosted on ASP.NET application. We want to track the build version of the whole app.
So this telemetry initializer
public class VersionInfoTelemetryInitializer : ITelemetryInitializer
{
public void Initialize(ITelemetry telemetry)
{
telemetry.Context.Component.Version =
typeof(Startup).Assembly.GetName().Version.ToString();
}
}
will be used in Gloabal.asax
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
var tc = TelemetryConfiguration.Active;
tc.InstrumentationKey = ConfigurationManager.AppSettings["AI Instrumentation Key"];
tc.TelemetryInitializers.Add(new VersionInfoTelemetryInitializer());
...
}
}
Server-side telemetry will have version information appended. But I am not able to do the same for the client-side telemetry. I have tried this
var appInsights = window.appInsights || function(config) {
// standard js snippet from azure portal
}({
instrumentationKey: '{{INSTRUMENTATIONKEY}}'
});
window.appInsights = appInsights;
window.appInsights.context.application.ver = 'some version number';
which results in following JS error
Uncaught TypeError: Cannot read property 'application' of undefined
I also tried
appInsights.queue.push(function () {
appInsights.context.addTelemetryInitializer(versionInfoTelemetryInitialier);
});
function versionInfoTelemetryInitialier(envelope) {
var telemetryItem = envelope.data.baseData;
telemetry.context.component.version = 'some version number';
}
which will warn with following message
AI: TelemetryInitializerFailed message:"One of telemetry initializers failed, telemetry
item will not be sent: TypeError" props:"{exception:[object Error]{ stack: 'TypeError:
Unable to get property 'component' of undefined or null reference\n at
versionInfoTelemetryInitialier (https://localhost:44301/landing/index:107:9)\n at
n.prototype._track (https://az416426.vo.msecnd.net/scripts/a/ai.0.js:1:65589)\n at
n.prototype.track...
What should I do so that client-side telemetry has version information attached.
i think your second attempt is very close. you need to do it via the queue, to make sure it occurs after all the AI scripts are actually loaded, so i think this is correct:
appInsights.queue.push(function () {
appInsights.context.addTelemetryInitializer(versionInfoTelemetryInitialier);
});
but in your initializer you switched from context.application.ver in your first example, to context.component.version in your second.
the javascript SDK is documented on the github repo:
https://github.com/Microsoft/ApplicationInsights-JS/blob/master/API-reference.md
and the examples there show:
context.application.ver: string
context.application.build : string
so shouldn't that initializer method be:
function versionInfoTelemetryInitialier(envelope) {
var telemetryItem = envelope.data.baseData;
telemetry.context.application.ver = 'some version number';
}

Node.js azure-storage TableService has no methods

I've been trying to connect to my Azure storage account, but I'm having some problems with the azure-storage module. Specifically, once I create a TableService object, the object only has a filter method on it. Two methods I've tried have been queryTables and createTableIfNotExist. For example, createTableIfNotExistreturns "TypeError: aztd.createTableIfNotExistis not a function". Source code is below.
var azure = require('azure-storage');
var aztd = azure.createTableService();
var azseg = azure.TableUtilities.entityGenerator;
console.log("AZSEG " + Object.getOwnPropertyNames(azseg).filter(function (p) { return typeof azseg[p] === 'function'; }));
console.log("AZTD " + Object.getOwnPropertyNames(aztd).filter(function (p) { return typeof aztd[p] === 'function'; }));
aztd.createTableIfNotExist('table1', function (e, result, res) {
if (result) console.log('Table created');
});
I'm not getting any additional errors aside from the function not found. The console log returns the functions for both variables:
AZSEG Entity,Int32,Int64,Binary,Boolean,String,Guid,Double,DateTime
AZTD filter
I can see the entityGenerator is created fine, but am I missing anything for the TableService?
Actually, the function name should be createTableIfNotExists, and it seems you have typed an invalid function name.
Also you can refer to source code of azure-storage-node on github to get all functions's info.

Categories

Resources