I try to execute this code and receive current blockchain block number
nodeInteraction.currentHeight('https://nodes.wavesplatform.com/').then((res) => {
console.log(res);
});
I did not forget to import the library
import { invokeScript, broadcast, nodeInteraction, waitForTx } from '#waves/waves-transactions';
This code is executed correctly.
nodeInteraction.accountData(dappaddress, baseUri).then((v) => {
window.dAppData = v;
if (v) {
window.dAppDataKeys = Object.keys(v);
console.log("dApp Account data:");
console.log(v);
console.log(JSON.stringify(v));
}
});
I'm using below library
https://wavesplatform.github.io/waves-transactions/globals.html#currentheight
I find an answer) I forgot to re-build my React app. Sorry.
Related
Apologies for asking this question - I know there are tons of information about async functions out there but I seem to have tried everything and cannot find a solution..
First of all let me outline the architecture of my program. There are two scripts: a main server script (node.js, express), which processes GET requests and provider script, which deals with the blockchain in the background to return some values. The server script is responsible for invoking a method that returns a value from the provider. The provider does all the work.
The snippet of the provider script:
getInfo(index, account, key) {
//Waiting on an asynchronous method, which does some work in the blockchain in the background; everything functions as it should be
try {
await this.getBlockchain
(
index
, account
, key
).then(result => {
// Here instead I invoke a SYNCHRONOUS method, which simply formats the response in a correct way
const reply = this.sendReply(result)
console.log(reply) //Logs the correct reply in the format in which the server is expecting it
return reply;
});
}
catch (error) {
return { error: 003, result: false };
}
}
The snippet of the server script:
server.get("/getAccount", async (req, res) => {
let index = req.query.index;
let account = req.query.account;
let key = req.query.key;
// Here I also check for the validity of the query values, irrelevant to this issue
// The provider class is imported as provider, hence, the provider.method (this has been tested many times before)
try {
await provider.getInfo(index, account, key).then(reply => {
const { error: infoError, result: infoValue } = reply
if (infoError == false) {
res.send(`${infoValue}`);
} else {
res.send(`${infoError}`);
};
});
}
catch (error) {
res.send("008");
}
}
);
I honestly have no idea how to approach this; I tried self-contained async function on the server side as well as different syntax but the reply is always undefined even though the reply from a synchronous call in the provider is correct.
Could someone help me to understand what I'm doing wrong? This is my first time working with async with numerous scripts and functions and I'm finding it very confusing.
Thank you so much!
With your current structure, you need to return the result of the await so that the top level of your function is returning something from the async function.
async getInfo(index, account, key) {
try {
let retVal = await this.getBlockchain(index, account, key).then(result => {
return this.sendReply(result);
});
return retVal;
} catch (error) {
return { error: 003, result: false };
}
}
But, really, it's a better coding style to not mix await and .then() and to just go with one style like this:
async getInfo(index, account, key) {
try {
let result = await this.getBlockchain(index, account, key);
return this.sendReply(result);
} catch (error) {
return { error: 003, result: false };
}
}
Note, this function never rejects because it's catching its own rejections and turning it into a resolved value. So, the caller cannot use .catch() to see errors. The caller must always check for the error property in the resolved object. This is not usually how you program with promises. It can be made to work, but often does not meet the expectations of the caller (as errors are usually communicated back via rejected promises).
This has to be a dup. but... Don't mix await and .then.
You simply try/catch around await.
try {
const reply = await provider.getInfo(index, account, key);
const { error: infoError, result: infoValue } = reply
if (infoError == false) {
res.send(`${infoValue}`);
} else {
res.send(`${infoError}`);
};
} catch (error) {
res.send(500);
}
We are using Testcafe for our regression tests and I would like to enhance the test logging of failed asserts by adding any messages from the browser console to the output. According to the Testcafe documentation, this code will print "The test has failed" in case the given element is not visible on the page:
await t.expect(Selector('#elementId').visible).ok("The test has failed");
According to the doco, the browser console messages can be read using the the t.getBrowserConsoleMessages method, but I have not been able to combine them into one statement like e.g.
await t.expect(Selector('#elementId').visible).ok(console.log(await t.getBrowserConsoleMessages()));
as this always processes the getBrowserConsoleMessages method and outputs the console messages, regardless of whether the assert is successful or not.
Is there a way to make this work only if the assert fails?
I seems you just need to call getBrowserConsoleMessages conditionally.
To get the expected behavior, you can use the following code:
import { Selector } from 'testcafe';
fixture`A set of examples that illustrate how to use TestCafe API`
.page`http://devexpress.github.io/testcafe/example/`;
test('Test1', async t => {
const isVisible = await Selector('#developer-name').visible;
if (!isVisible)
console.log(await t.getBrowserConsoleMessages())
await t.expect(isVisible).ok();
});
test('Test2', async t => {
const isVisible = await Selector('#developer-name2').visible;
if (!isVisible)
console.log(await t.getBrowserConsoleMessages())
await t.expect(isVisible).ok();
});
Here is how I got this working myself:
import { Selector } from 'testcafe';
async function objToString (obj) {
return Object.entries(obj).reduce((str, [p, val]) => {
return `${str}${p}::${val}\n`;
}, '');
}
fixture('My test')
.page('https://myurl.com')
test('Test1', async t => {
....
await t.expect(Selector('#elementId').visible).ok(await objToString(await browser.getBrowserConsoleMessages()));
....
});
im searching for an idea to fix my problem. First of all, there is a server.exe software, that can load some stuff. But if i change something, it needs a restart, but not, if i use a json file to store account names. Look:
const allowedPlayers =
[
"Socialclubuser1",
"Socialclubuser2",
"Socialclubuser3"
]
mp.events.add("playerJoin", (player) => {
if (!allowedPlayers.includes(player.socialClub)) {
player.notify('Youre not whitelisted!');
}
});
mp.events.add("playerJoin", (player) => {
if (!allowedPlayers.includes(player.socialClub)) {
player.kick('Youre not whitelisted!');
}
});
i would use account.json, and insert there the stuff but how?
greetings
Create an account.json file and require it using require on start.
// account.json
// ["Socialclubuser1", "Socialclubuser2", "Socialclubuser3"]
const allowedPlayers = require("./account.json");
// rest of the code
mp.events.add("playerJoin", player => {
if (allowedPlayers.indexOf(player.socialClub) === -1) {
player.notify("Youre not whitelisted!");
player.kick("Youre not whitelisted!");
}
});
I'm not sure of how to adequately achieve my desired control flow using promises/bluebird.
Essentially I have a database with X 'tasks' stored and each needs to be loaded and executed sequentially. I don't want to run more than one task concurrently and the entire code must continue executing indefinitely.
I have achieved this with the following code so far:
export default function syncLoop() {
getNextTaskRunner().then((taskRunner) => {
if (taskRunner) {
taskRunner.startTask()
.then(syncLoop)
.catch((error) => {
throw new Error(error);
});
} else {
syncLoop();
}
});
}
getNextTaskRunner() simply loads and resolves with the next task from the database (calc'd based on timestamps). Or it resolves with null (no task avail).
taskRunner.startTask() resolves with null when the full task has completed.
I've been advised that the way it is structured (recursive /w promises) could lead to stack issues after it has been running for some time.
What I've thought about doing is to restructure it to something like:
let running = false;
setInterval(() => {
if (!running) {
running = true;
getNextTaskRunner().then((taskRunner) => {
if (taskRunner) {
taskRunner.startTask()
.then(() => {
running = false;
})
.catch((error) => {
log.error(error);
});
} else {
running = false;
}
});
}
}, 5000);
Or as yet another possibility, using event emitters in some form?
task.on('complete', nextTask());
Thoughts and advice will be greatly appreciated!
What stack issues? The way you've written your code is perfectly fine as long as getNextTaskRunner is truly async (i.e. it gives control back to the main loop at some point, e.g. if it does async io). There is no recursion in your code in that case. Whoever told you that is mistaken.
Though you might want to add a setTimeout somewhere so you won't flood your db with requests. Plus it will help you if getNextTaskRunner will no longer be sync (due to for example in memory caching):
export default function syncLoop() {
setTimeout(() => {
getNextTaskRunner().then((taskRunner) => {
if (taskRunner) {
taskRunner.startTask()
.then(syncLoop)
.catch((error) => {
throw new Error(error);
});
} else {
syncLoop();
}
});
}, 2000);
}
I've just started angular 2. I've done an angular2 sample as given in the https://angular.io/guide/quickstart
when I run the project in Firefox using
npm start
command in terminal, the connection get disconnected after output showing once.Error showing like
The connection to ws://localhost:3000/browser-sync/socket.io/?EIO=3&transport=websocket&sid=6YFGHWy7oD7T7qioAAAA was interrupted while the page was loading
Any idea about how to fix this issue ?
I don't know how you manage your web socket but you could consider using the following code. This idea is to wrap the web socket into an observable.
For this you could use a service like below. The initializeWebSocket will create a shared observable (hot) to wrap a WebSocket object.
export class WebSocketService {
initializeWebSocket(url) {
this.wsObservable = Observable.create((observer) => {
this.ws = new WebSocket(url);
this.ws.onopen = (e) => {
(...)
};
this.ws.onclose = (e) => {
if (e.wasClean) {
observer.complete();
} else {
observer.error(e);
}
};
this.ws.onerror = (e) => {
observer.error(e);
}
this.ws.onmessage = (e) => {
observer.next(JSON.parse(e.data));
}
return () => {
this.ws.close();
};
}).share();
}
}
You could add a sendData to send data on the web socket:
export class WebSocketService {
(...)
sendData(message) {
this.ws.send(JSON.stringify(message));
}
}
The last point is to make things a bit robust, i.e. filter received messages based on a criteria and implement retry when there is a disconnection. For this, you need to wrap our initial websocket observable into another one. This way we can support retries when the connection is lost and integrate filtering on criteria like the client identifier (in the sample the received data is JSON and contains a sender attribute).
export class WebSocketService {
(...)
createClientObservable(clientId) {
return Observable.create((observer) => {
let subscription = this.wsObservable
.filter((data) => data.sender!==clientId)
.subscribe(observer);
return () => {
subscription.unsubscribe();
};
}).retryWhen((errors) => {
return Observable.timer(3000);
});
}
}
You can see that deconnections are handled in this code using the retryWhen operator of observable.