Wait for WebHID response to be ready [closed] - javascript

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 months ago.
Improve this question
I'm sending data to the target device using device.sendReport(reportID, dataBuffer) of WebHID, but trying to read the response before it gets ready (i.e) the response takes time to be generated.
For now by setting timeout for 10ms, I'm able to get the response. Would like to know if there are any better solution for this.

You haven't said how the device provides the response but I assume that it is in the form of an input report. In that case the Promise returned by sendReport() isn't particularly interesting but instead you want to listen for an inputreport event that will be fired at the HIDDevice. If you want you can turn this into a Promise like this,
const response = new Promise((resolve) => {
device.addEventListener('inputreport', resolve, { once: true });
});
await device.sendReport(...your data...);
const { reportId, data } = await response;
Once the response is received it will be stored in data.
Note that this assumes that the device only generates input reports in response to a request. For a device with more complex communications you may want to have an inputreport event listener registered at all times and process input reports based on their report ID or other factors. HID does not support any backpressure so if you don't have an inputreport event listener registered when a report is sent by the device it will be discarded.

For this type of action you should use asynchronous code. When sending/receiving things to or from a server, this action is a 'Promise' which is asynchronous.
It'll look something like this (using the fetch api as an example):
With callbacks (which are optional)
myFunction = () => {
fetch('POST', data)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.warn(error);
});
}
With async/await. This is not recommended in most cases, as this assumes that the request will succeed.
myFunction = async () => {
const response = await fetch('POST', data);
console.log(response);
}

Related

how to use websocket like an api [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed last month.
Improve this question
I have websocket connection between client(browser) & server.
Problem is, sometimes I request a data through websocket.
But since websocket works like an event, I cannot manage my code efficiently.
I can send websocket message in a function but then I have to listen and handle it on the event listener.
Below is example.
const ws = new WebSocket("ws://whatever");
function handleClickBtn() {
ws.send('request something');
// cannot get response here
}
ws.onmessage = function (event) {
console.log(`response comes here: ${event.data}`);
}
It seems harder to maintain my code since you have to jump between request and response.
If I've used REST API, it would been easier with async/await syntax.
What kind of technique can be used here?
You'll need to think in async terms and indeed handle many potential in-flight requests at the same time. To be able to do this, you will need to be able to relate the incoming responses to requests you sent previously. For example, you could add random ids to your requests, and the response to it will contain the same id. E.g.:
Request:
[82512903521, "fetch-data", "param1", "param2"]
Response:
[82512903521, {"some": "returned", "data": ...}]
Then internally you keep a list of request ids you sent, together with an appropriate callback function which you'll trigger when the corresponding response returns. E.g. something like:
const requests = {};
function request(callback, ...params) {
const id = randomId();
ws.send([id, ...params])
requests[id] = callback;
}
ws.onmessage = function (event) {
const [id, data] = event.data;
requests[id](data);
}
There are existing protocols and libraries that implement this kind of this, for example WAMP.

How to get return value of smart contract by calling encoded function [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
I have encoded function of my smart contract, which has methodID and parameters i.e. 0xf7ea7a3d4000000000000000000015000000000000000000ff7f0000b200000000f7ea7a............... Suppose, in this encoded function, there are also two arguments, one is uint and the other is a string. This encoded function actually is a getter (not changing status) of my contract (means in ABI its stateMutability =view) and also it return a value i.e. totalSupply. Now, I want to call this function through web3js/nodejs, as below. This code gives me transaction receipt/hash, as expected, but I am interested to retrieve the getter function return value i.e. totalSupply;
try {
await web3.eth.sendTransaction(
{
from: account1,
to: myContAddr,
data: myFunc
}).then(function (res) {
console.log("Normal Getter", res);
});
} catch (error) {
console.log(" Normal Getters: ERROR !");
}
One possible solution is to extract function Signature/methodID (which is easy for me) from given encoded function and its parameters (yet, not known to me how to decode parameters) and call the function like this .. i.e.
try {
res = await myContractInstance.methods[myFuncID](????).call({ from: account1 }) // without parameters
console.log("Getter output", res);
} catch (error) {
console.log("Getter output: ERROR !", error);
}
So, my questions are
How to decode parameters from above mentioned encoded function, to proceed as per my mentioned solution (if my solution is correct)?
Or is there any other feasible/easy procedure to call such an encoded (getter) function?

firebase how to get values from database (website) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to get values 0 from firebase realtime database as variable in JavaScript. have easy way to get it? (I tried to find from this website but there is only have android).
First you must get a reference to where the data is stored.
let ref = firebase.database().ref("database/path/to/limitedorder/Apoint");
Next, you must choose how you would like to be notified of data changes. For your use case, this would be subscribing to the 'value' event only once. This will return a Promise that resolves with the desired data.
let valuePromise = ref.once('value');
You then need to chain to the promise to handle/manipulate the data returned by the server and/or handle any errors.
valuePromise.then((dataSnapshot) => {
let desiredValue = dataSnapshot.val();
console.log("Desired value: ", desiredValue);
})
.catch((error) => {
console.log("An error occurred:", error);
})
Bringing this altogether gives:
firebase.database().ref("database/path/to/limitedorder/Apoint").once('value')
.then((dataSnapshot) => {
let desiredValue = dataSnapshot.val();
console.log("Desired value: ", desiredValue);
})
.catch((error) => {
console.log("An error occurred:", error);
})
Detailed explanation of these steps is provided in the Firebase RTDB for Web documentation.

AJAX - Displaying current status of the connection to users [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I will need to pull data from many datasources - this is a time-consuming process.
If user sends the form the program pulls data from 7 tables ( using ajax )
I would like to provide an information what is actually going on ,for example "Pulling data from table1" , "Pulling data from table2" and so on.
but have no idea how to do this - Is there a good standard for this kind of task ?
I am using python/django as a backend
Thanks in advance
You can use the XHR onprogress function to stream data in JavaScript. The function gets called periodically whenever data is flushed from the server. So use sys.stdout.flush() in Python to force a flush whenever you want to display the current status.
test.py
import sys
import time
for x in range(5):
print(x)
sys.stdout.flush()
time.sleep(1)
test.html
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<button id="btn">Begin Stream</button>
<div id="app"></div>
<script>
$(function() {
$("#btn").on("click", () => {
$.ajax('test.py', {
xhrFields: {
onprogress: (e) => {
$("#app").html(e.currentTarget.response);
}
}
})
.done((data) => {
$("#app").html(`DONE: ${data}`);
})
.fail((data) => {
$("#app").html(`ERROR: ${data}`);
});
});
});
</script>

Dealing with pagination in database with AngularJS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I'm trying to get all data from a custom API (flask with PostgresSQL database) using '$http' service in my controller but the api and database is constructed with pagination which means that if I wan't to access data a need to create services like this:
/*FIRST PAGE*/
$http.get("/api/test", testData)
.success(...)
/*SECOND PAGE*/
$http.get("/api/test?page=2", testData)
.success(...)
This is obviously not good solution but it works ! So could you guide me how to deal with this situation better ? because i know that this api contains over 1 thousand pages...
Cheers !
This is decribed in the official documentation.
Angular's $http service supports config param (second param of .get) which supports params parameter and do all the concatentaion with proper encoding etc etc for you.
params – {Object.<string|Object>} – Map of strings or objects which
will be serialized with the paramSerializer and appended as GET
parameters.
So you can do
angular
.module('xxx')
.factory('getPagedData', function ($http) {
return function(page) {
return $http.get("/api/test", { params: { page: page } });
}
});
And use it like this:
function someController(getPagedData) {
getPagedData(2).then(...); // will do GET /api/test?page=2
}
Also note, the .success method is deprecated. It is even removed in Angular 1.6. Use .then instead.
You can simply just pass a variable every time you want to page to the next data set. So you would have:
$http.get("/api/test?page="+ pageNum, testData).success(..)
Hope this helps!
Try creating a service that uses promises to access the data and break apart the data the way you want:
function getTestData(testData) {
return $http.get("/api/test", testData)
.then(function(response){ //Promise is successful create an object to store the data
}, handleError);
function testError(response){//Handle any errors if the promise fails
return response;
}
}
While this seems like a logical solution...
/* SERVICE */
var baseUrl = "/api/test";
MyService.getTests = function(page, testData) {
var pageParams = "";
if (page > 1) {
pageParams = "?page="+page;
}
return $http.get(baseUrl+pageParams, testData).success().error();
}
...GET requests don't allow you to send any data. I'm not sure how you plan to send testData to a $http.get request. The second parameter of a GET request is the config object, which makes your service much simpler.
var baseUrl = "/api/test";
MyService.getTests = function(page, testData) {
return $http.get(baseUrl, {params: {page: page}) //becomes /api/test?page=1
.success()
.error();
}

Categories

Resources