Destructuring from props is not working inside an async function while it's working fine if I use it using this.props.
This is for a react-native app already in production which suddenly started giving this error 2 days back.
I've tried upgrading babel using this
But no success so far.
If I use this.props.getLoginData instead, it works fine
If I use following function, it's erroneous:
yo = async () => { // with async
const { getLoginData } = this.props; // error
};
While the following function works fine:
yo = () => { // without async
const { getLoginData } = this.props;
console.log(getLoginData); // works fine
};
This also works fine:
yo = async () => { // with async
console.log(this.props.getLoginData); // works fine
};
I expect both of the scenarios to run fine.
Please clone and run this repo to reproduce this bug.
Please find the steps to run the project and environment info in README.md.
P.S.: You will find the error in console( Press ⌘⌥I )
It looks like a dependency of babel is the cause of the issue in my case.
When I look in my package-lock.json, and search for plugin-transform-regenerator I see version 7.4.5. Locking the version to 7.4.4 by adding it to my package.json allows me to build without issue.
This problem would have been easier to track down if I was not ignoring my package-lock.json.
In summary,
npm i -E #babel/plugin-transform-regenerator#7.4.4
I've encountered the same problem.
Using babel version 7.4.4 didn't help me, but I've found another solution that worked - wrapping the destructure in try-catch block.
I still don't know why this problem happens though - will update when I do.
________UPDATE_______
Eventually, the solution #makenova offered worked (Thanks man!).
What I had to do is to remove all node modules + package-lock, then run
npm i -E #babel/plugin-transform-regenerator#7.4.4
and after that run
npm i
Before that I've used yarn and it didn't do the trick.
Update:
nicolo-ribaudo fixed the issue here: https://github.com/facebook/regenerator/pull/377
An alternative solution is to force the regenerator-transform to use ~0.13.0 as suggested by nicolo-ribaudo.
If you are using yarn, add this to your package.json:
"resolutions": {
"regenerator-transform": "~0.13.0"
}
If you are using npm:
Install it as a devDependency
Delete package-lock.json
Re-install dependencies
I've a async function, when destructuring and save const show me error: Possible Unhandled Promise Rejection (id: 0): Error: “userOperations” is read-only , this worked for me (change let by const):
https://github.com/facebook/regenerator/issues/375#issuecomment-527209159
Related
**Hi, I don't know what happen here, it's something release with a dependence, It's a code that I didn't write, it's a bundle and I use expo to run my code but, can't open my app because that error please help!! it's for a college project **
function resolveDependencies(parentPath, dependencies, options) {
const resolve = (parentPath, result) => {
const relativePath = result.name;
try {
return [
relativePath,
{
absolutePath: options.resolve(parentPath, relativePath),
data: result
}
];
} catch (error) {
Ignore unavailable optional dependencies. They are guarded with a try-catch block and will be handled during runtime.
if (result.data.isOptional !== true) {
throw error;
}
}
return undefined;
};
const resolved = dependencies.reduce((list, result) => {
const resolvedPath = resolve(parentPath, result);
if (resolvedPath) {
list.push(resolvedPath);
}
return list;
}, []);
return new Map(resolved);
}
Re-traverse the dependency graph in DFS order to reorder the modules and
guarantee the same order between runs. This method mutates the passed graph.
I had the same issue on the latest expo-cli 4.8.1.
For me helped following steps
downgrade from 4.8.1 -> 4.7.3 npm install -g expo-cli#~4.7.3
clear npm cache by executing npm cache clean --force
clear local user cache by deleting everything in C:\Users<user>\AppData\Local\Temp folder.
After these steps, it is working again
I had this issue when running expo start --dev-client on expo-cli version 4.12.1.
I solved it by adding the --clear flag (which clears the Metro bundler cache)
Deleting the system cache Temp folder content will work,
When I face the same issue this solution help me to solve the problem
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.
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.
I have error in the following below test. My node version is : v12.10.0. is there any alternative of setTimeout?
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
The Error log is as
Call retries were exceeded
at ChildProcessWorker.initialize (../../../node_modules/jest-worker/build/workers/ChildProcessWorker.js:230:21)
just add jest.useFakeTimers(); after your imports
...
jest.useFakeTimers();
test('demo code', async () => {
const cc = await projectSetup(project);
const onNotification = jest.fn();
cc.sendNotification();
await waitForExpect(() => {
expect(onNotification).toHaveBeenCalledTimes(2);
});
});
it works in my code
In my case, the actual problem was with the promise handling.
I got the same issue when I was running all my test cases in one go with the jest.
Solution:
Try running one test separately then see what error is coming.
I got the below error after running one problematic test separately where earlier I was getting the Call retries were exceeded:
[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason "TypeError: Cannot read property 'code' of undefined".] {
code: 'ERR_UNHANDLED_REJECTION'
}
With this, I was sure that the problem is with the catch block and when I added it in the async service API function then the test case worked perfectly fine.
Maybe you can also try the same and see if it works for you or not.
I am using the below config:
node: 15.13.0
npm: 7.8.0
jest: 26.6.3
Try running npm doctor using the latest npm version. It's a great tool and it helped me diagnose permission and ownership issues right away.
Takeaway:
Verify File/Folder Permissions & Ownership
Encountered same error when updating the vue-jest version to below listed versions
#vue/vue3-jest: ^27.0.0-alpha.4
#vue/cli-plugin-unit-jest: ~5.0.0,
node: v17.9.0 or v16.14.2
Error disappeared, once downgraded it to node version v14.x.x
Hunch is - the latest node versions are not compatible with the dependencies.
I was able to run the test's successfully doing the following;
Install npm i -D jest-canvas-mock
Update the jest.config.ts file to have:
export default {
...
testEnvironment: "jsdom",
setupFiles: ["jest-canvas-mock"],
}
I observe that In angular 2 there is no finally block for promise API
angular 1 :
loadUsers() {
fetch('/api/users').then((response) => {
return response.json();
}).then((data) => {
this.users = data;
}).catch((ex) => {
console.error('Error fetching users', ex);
}).finally(() => {
this.userLoaded = true;
};
Assuming I have to do same thing in angular 2
How to add finally block in angular 2 promise , as of now there are only then & catch blocks available in angular 2. If not finally then is there any way to add cleanup code after execution of each method , where do i write code to do finally block activities ?
The easiest way to do this is to use the promise.finally shim.
Add it with npm install --save promise.prototype.finally
Add the typings: npm install --save-dev #types/promise.prototype.finally
In your main class, before bootstrapping the application, add the following code:
import { shim } from 'promise.prototype.finally';
shim();
You should now be able to use finally on your promises.
This is usually done using Promise.always. This takes one function, and adds a new .then on the promise that gives the same function for both success and fail states. If the function is not available in the given promise-based environment, it's pretty easy to polyfill in.
Promise.always = function(p, fn) {
return p.then(fn, fn);
}
usage:
var prom = fetch('/api/users').then...
Promise.always(prom, () => {
this.userLoaded = true;
});
return prom;
Modern solution in 2019-2020
First of all, you should avoid manually adding polyfills without a good reason for it, don't do it blindly because you've read it somewhere.
The problem you encounter has two sides: typing declarations and the implementation.
In order to use Promise.finally in your code without typing errors you should add es2018.promise to the lib option in your tsconfig.json file.
For modern projects you should use the following configuration (which is default in Angular 8):
{
"compilerOptions": {
…
"lib": [
"es2018",
"dom"
]
}
}
This will fix the typing errors you have in the editor.
Also, according to the docs and my observations the correct polyfill for Promise.finally will be added by the Angular compiler automatically, you don't have to install or add anything.
But, in general, you could add a polyfill (only if it is proven to be required) in ./src/polyfills.ts file using core-js library. Always try to use core-js instead of other libraries, cause it's an industry standard and it's used by Angular internally.
For example, Promise.finally polyfill could be added like this:
import 'core-js/features/promise/finally';
See more at core-js documentation.
Also, make sure to read browser-support and differential-loading articles of Angular documentation.