I've got a very simple function set up to (eventually) load data from AsyncStorage. Currently I'm not even using AsyncStorage, but I'm just trying to make sure I'm using Promises
correctly. Here is my simple code to get such a Promise
:
Storage.ts
:
export async function poll(key: string): Promise<any> {
try {
console.log("polling");
return new Promise((resolve, reject) => {
resolve("Promised value.");
});
} catch (e) {
// TODO: Log something.
}
}
Then I'm trying to retrieve the promise here in my functional component:
ExampleAsyncComponent.tsx
:
import React, { useEffect, useState } from "react";
import { ReactElement } from "react-native/node_modules/@types/react";
import { poll } from "./Storage";
import { Text, View } from "react-native";
export default function ExampleAsyncComponent(): ReactElement {
const [value, setValue] = useState<any>(null);
const [refreshCount, setRefreshCount] = useState<number>(0);
const loadedValuePromise: Promise<any> = poll("some.key");
const updateValue = async () => {
loadedValuePromise.then((v) => {
setRefreshCount(refreshCount + 1);
console.log("then count: " + refreshCount);
setValue(v);
});
};
useEffect(() => {
setInterval(() => {
updateValue();
}, 2000);
});
return (<View><Text>hello</Text></View>);
}
I've added some logs to the console to try and visualize/debug how all of this is working, but I'm getting a LOT more logs than I would've expected. With the code above, I would've expected "polling"
to be printed out once and then every couple of seconds I would see "then count: x"
. However, it looks like I'm starting up a bunch of promises (and in my mind, I think that means I'm starting up a bunch of threads). The longer this application runs in the browser (where I'm debugging my React Native app) the crazier the output gets, but here's the output from my app running for just a few seconds:
So I guess I have a couple of questions. Is this to be expected? If so, should I be expiring my promises somehow (I haven't found any examples of that yet)? If this isn't to be expected, what am I doing wrong?