Javascript promise never resolves - javascript

I am using rotateByDegrees from a library called node-poweredup in a typescript project:
motor.rotateByDegrees(20,10).then(function(value) {console.log("test");}, function(value) {console.log("error");});
I would expect to see "test" after successful completion, but the promise never resolves. If I use await, it hangs on the await line forever.
Replicating the syntax that appears to be used in the rotateByDegrees function:
let promise = new Promise((resolve) => { return resolve(); });
does not compile, I get error TS2794: Expected 1 arguments, but got 0. Did you forget to include 'void' in your type argument to 'Promise'? I can make it compile and behave as expected with resolve(true), but how does it compile in the library then? Do I misunderstand promises? Some feature in typescript? A bug in the library? I am a newbie to JavaScript, I don't want to over-complicate this question by including irrelevant details. If you can give me hints on what I am missing and how to debug this, I can provide all relevant details.

Thanks to the helpful comments I was able to narrow it down to the compilation of the library. I did in fact not use a pre-compiled binary but had to compile the library myself using electron-rebuild to make the bluetooth adapter work. I did the following test:
git clone https://github.com/nathankellenicki/node-poweredup.git
cd node-poweredup
npm install
npm run build
this compiles without error. I created the following test file
const PoweredUP = require("node-poweredup");
const poweredUP = new PoweredUP.PoweredUP();
poweredUP.scan(); // Start scanning for hubs
console.log("Looking for Hubs...");
poweredUP.on("discover", async (hub) => { // Wait to discover hubs
await hub.connect(); // Connect to hub
console.log(`Connected to ${hub.name}!`);
const motorA = await hub.waitForDeviceAtPort("A"); // Make sure a motor is plugged into port A
motorA.rotateByDegrees(20,10).then(function(value) {console.log("test");});
});
and get the expected output:
node-poweredup$ node test.js
Looking for Hubs...
Connected to MyHub2!
test
Connected to MyHub3!
test
When I changed the first line to
const PoweredUP = require(".");
to make it use my self-compiled binary I get
node-poweredup$ node test.js
Looking for Hubs...
Connected to MyHub2!
Connected to MyHub3!
Of course this is only a partial answer because I still don't know why it compiles differently on my machine, but at least I have an idea where to start searching for the problem.

Related

My Javascript file won't run because of bigint error

I am trying to use #metaplex/js to do some NFT minting. Usually my .js files work properly but when I run the file this error comes up.
bigint: Failed to load bindings, pure JS will be used (try npm run rebuild?)
I don't really get what that means. So, I tried to run npm run rebuild but rebuild is said to be a missing script and I couldn't find a way to install it.
Here is my code:
import { Connection, programs} from "#metaplex/js";
import { Loader } from "#solana/web3.js";
const { metadata: {Metadata}} = programs;
const connection = new Connection("devnet");
const tokenPublicKey = 'my_adress';
const run = async() => {
try{
const ownedMetadata = await Metadata.Loader(connection,tokenPublicKey)
console.log(ownedMetadata)
}
catch{
console.log('Failed to fetch')
}
};
run();
If you have any idea, or simply an explanation of what my error means, I'd be grateful.
You are getting this error because a nested dependency has a compilation step that might not succeed in your platform. This issue provides a good explanation.
[...] This happens because one of our dependencies (bigint-buffer) runs a compilation step on installation and this can step may fail for a couple of reasons. One of the reasons is that your system might not have the build-tools the library is looking for. You can install these build tools on Windows (see https://www.npmjs.com/package/windows-build-tools), but you don't actually need to as it automatically falls back to a pure JS solution instead. Though I agree... that warning is very annoying.
However, this should give you a warning and still allow you to compile your code.
It is worth noting that the current JS SDK from Metaplex is going to be deprecated in favour of the new one: https://github.com/metaplex-foundation/js-next
With the new JS SDK, you can fetch an NFT using the following piece of code.
import { Metaplex } from "#metaplex-foundation/js";
import { Connection, clusterApiUrl } from "#solana/web3.js";
const connection = new Connection(clusterApiUrl("mainnet-beta"));
const metaplex = new Metaplex(connection);
const mintAddress = new PublicKey("ATe3DymKZadrUoqAMn7HSpraxE4gB88uo1L9zLGmzJeL");
const nft = await metaplex.nfts().findByMint({ mintAddress });

how to open node in a new terminal from cmd?

when I type start node into the cmd it starts up a new node terminal like this:
but how do I get it to run a script in the node terminal and close it after it's done?
maybe something like this?
start node "index.js" (when I try this it opens a terminal then immediately closes)
index.js:
console.log('hello there!');
await new Promise(r=>setTimeout(r,3000));
Top-level awaits aren't supported in Node versions prior to 14.18.0; there is a helpful discussion on GitHub as to why.
Since you're running v14.17.6, you'll need to wrap your code in an anonymous async function, then invoke it with ():
(async () => {
console.log('hello there!');
await new Promise(r=>setTimeout(r,3000));
})();
The resulting Node terminal will await for your timeout period before being closed.
(It may also behoove those reading this answer to ensure that they are correctly referencing the script they wish to execute relative to their command line's current working directory; see comment below by #cakelover.)

Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum

I'm enthusiastic about Deno so I'm giving it a try. Found a tutorial on building a REST API here.
So, when I'm trying to run it, I get this InvalidData error:
error: Uncaught InvalidData: data did not match any variant of untagged enum ArgsEnum
at unwrapResponse ($deno$/ops/dispatch_json.ts:43:11)
at Object.sendAsync ($deno$/ops/dispatch_json.ts:98:10)
at async Object.connect ($deno$/net.ts:216:11)
at async Connection.startup (https://deno.land/x/postgres/connection.ts:138:17)
at async Client.connect (https://deno.land/x/postgres/client.ts:14:5)
at async Database.connect (file:///Users/svenhaaf/git/deno/logrocket_deno_api/db/database.js:17:5)
Now, it looks to me that something is wrong when trying to connect to the database, but I can't really figure out what.
What does this InvalidData error mean? How should I fix this?
FYI my deno --version prints:
deno 0.42.0
v8 8.2.308
typescript 3.8.3
Code:
I cloned the repo from https://github.com/diogosouza/logrocket_deno_api, and in config.js, I edited line 1 from const env = Deno.env() to const env = Deno.env, since it looks like Deno.env became an object instead of a method.
The tutorial is not using versioned URLs, and deno-postgres version that is being used is not compatible with v0.42.0, since https://deno.land/x/postgres/mod.ts is pulling from master
Change db/database.js to import from https://deno.land/x/postgres#v0.3.11/mod.ts, since v0.3.11 is the correct version for Deno v0.42.0
import { Client } from "https://deno.land/x/postgres#v0.3.11/mod.ts";
Remember to always use the version in the URL if you don't want the code to stop working when a new Deno or package version is released.

Running a test with Mocha also launches the main program

I'm trying to use Mocha to test a CLI app. The tests are running fine but, when I launch the testing procedure, it also launches the main app:
$ npm run test
> standardize-js#0.2.2 test C:\Users\Gaspard\Documents\Code\standardize-js
> mocha "./source/**/*.spec.js"
? Choose your project language or framework (Use arrow keys) //<-- THIS IS THE PROGRAM
> Javascript
Typescript
AngularJS
Main function //<-- THIS IS THE TEST
ask if the configuration is valid
Configuration is not valid, terminating program.
√ should return false if the configuration is not accepted
1 passing (29ms)
I'm kind of new to the testing world and I'm really struggling to understand what I'm doing wrong.
Here is the NPM script used to launch mocha :
"test": "mocha \"./source/**/*.spec.js\""
Here is my testing method:
/* eslint-disable func-names */
const { expect } = require("chai");
const main = require("./index").test;
describe("Main function", function() {
describe("ask if the configuration is valid", function() {
it("should return false if the configuration is not accepted", function() {
const fakeAnswer = false;
expect(main.validateConfiguration(fakeAnswer)).to.equal(false);
});
});
});
And here is my index.js file:
function validateConfiguration(answer) {
if (answer === false) {
console.log(chalk.red("Configuration is not valid, terminating program."));
return false;
}
return true;
}
const run = async () => {
//MAIN FUNCTION
};
run();
// Export functions and variables to be able to test
exports.test = {
validateConfiguration
};
It's not a problem with mocha. It is simply now node.js modules work.
When you do this:
const main = require("./index").test;
Node.js will execute index.js and then check the value of module.exports. If the module (index.js) sets or modifies module.exports then node will export it for use by require(). But note, in order for node to know that the module has exported anything it must execute the javascript file.
Node.js does not have any ability to parse and analyze javascript syntax (that's V8's job). Unlike other languages such as C or Java, modules in node.js are not implemented at the syntax level. Therefore the javascript language does not need to be modified (eg. ES6 modules) for node.js to support modules. Modules are simply implemented as a design pattern.
In your index.js file you call run:
run();
When require() loads index.js it will therefore also cause run() to be called.
Test libraries, not main
The solution to this is to implement your own logic as modules and test that, not test index.js:
mylib.js:
function validateConfiguration(answer) {
if (answer === false) {
console.log(chalk.red("Configuration is not valid, terminating program."));
return false;
}
return true;
}
// Export functions and variables to be able to test
exports.test = { validateConfiguration };
index.js:
const validateConfiguration = require("./mylib").test;
const run = async () => {
//MAIN FUNCTION
};
run();
You can now use your test script as written.
How can you not test code??
The strategy to keep index.js bug free without testing is to remove all logic from it except for the minimum amount of code to wire all your other code up together to run the app. The code should be as simple as "Hello World". That way, the code in main is so small and so simple that you can test it for bugs using your eyeballs.
Any code in index.js that causes a bug should be refactored into its own library so that it can be tested separately. There are a small handful of corner cases, such as loading environment variables or opening port 80 where you can't really separate into a library because they literally are wiring logic. For such cases you just have to be really careful.
It's calling run because you are telling it to right after defining the method.

Testing node.js Command Line tool with Jest

I'm currently trying to get some test coverage for a command line tool I built in node with Jest. My code is split up in modles, most of which have asynchronous http requests that I'm trying to mock. I'm wondering if there is a way to mock these requests that exist inside the module functions?
module.exports = function() {
client.apiGet() // How do I mock this?
.then(() => {
// more logic, runs several fs operations
})
.catch((err) => { console.error(err) });
}
You will need to mock the client module. I assume you had require or import it further up. Once you have it mocked you can decide to either stub all of it's methods' implementations or just the apiGet.
https://jestjs.io/docs/en/manual-mocks.
Finally, you will probably use the .resolves and .rejects to have the proper expectation.
https://jestjs.io/docs/en/expect#resolves
#Koen Van Gilst wrote a great blog about mocking API calls with Jest:
https://hackernoon.com/api-testing-with-jest-d1ab74005c0a
Hope this sends you in the right direction

Categories