The promise on executesql on Ionic-native sqlite object is not working in NodeJS 16.
this.getTransactionDbConnection().executeSql(OfflineService.SQL_GET_METADATA, [key])
.then((data)
If I divide above call into 2 parts like below , then I am able to see both console statements
console.log(transDb); let sqlResponse =
transDb.executeSql(OfflineService.SQL_GET_METADATA, [key]);
console.log(sqlResponse); sqlResponse.then(data)``` --------- This line is not responding.
I do understand, I need to put async await and check.
But Observer will fail. That will be then a bigger change.
Same code works on NodeJS 12.
In package.json dependencies, I am using
Ionic-native/sqlite : ^4.7.0,
cordova-sqlite-storage : ^2.5.0
My complete code -
getMetadata(key: string): Observable<string> {
return Observable.create((observer: Observer<string>) => {
this.getTransactionDbConnection().executeSql(OfflineService.SQL_GET_METADATA, [key])
.then((data) => {
console.log('After executesql',JSON.stringify(data));
const metadataValue = data.rows.length > 0 ? data.rows.item(0).VALUE : '';
console.log('Get metadata.', key, metadataValue);
observer.next(metadataValue);
observer.complete();
}).catch(e => {
console.error('Error occurred while trying to get metadata.', e.message);
observer.error(e);
});
});
}
Related
I've followed expo documentation to include this library to my expo managed react native application. SecureStore
I am using:
expo: 44.0.5
react-native: 0.64.3 (SDK 44)
expo-secure-store: 11.1.0
expo-dev-client: 0.8.6
react & react-dom 18.0.0
typescript
In my App.tsx:
import 'expo-dev-client'
import { deleteValueFor, getValueFor, save } from './src/core/infrastructure/storage/secureStore'
import { REFRESH_TOKEN } from './src/core/infrastructure/config/constants'
....
export default function App(): JSX.Element | null {
....
useEffect(() => {
;(async () => {
try {
const refreshToken = await getValueFor(REFRESH_TOKEN)
...
// things I do whit refreshToken
...
} catch (e) {
console.warn(e)
}
})()
}, [])
const login = async (authUser: AuthUser) => {
const { token, refreshToken, user } = authUser
if (!user) {
throw 'Error al obtener los datos del usuario desde el context'
}
setToken(token)
save({ key: REFRESH_TOKEN, value: refreshToken }) // <---- The error occurs here
}
}
In secureStore.ts
import * as SecureStore from 'expo-secure-store'
export async function save({ key, value }: { key: string; value: string }): Promise<void> {
await SecureStore.setItemAsync(key, value)
}
export async function getValueFor(key: string): Promise<string | null> {
try {
return await SecureStore.getItemAsync(key)
} catch (error) {
return null
}
}
export async function deleteValueFor(key: string): Promise<void> {
await SecureStore.deleteItemAsync(key)
}
export async function checkAvailability(): Promise<boolean> {
return SecureStore.isAvailableAsync()
}
I execute this command to run the app in simulator:
expo start --dev-client --ios
The application is running fine inside the simulator, no errors with that. And after I fill login credentials and press in login button, this is the error message I'm getting:
[Unhandled promise rejection: Error: The method or property SecureStore.setItemAsync is not available on ios, are you sure you've linked all the native dependencies properly?]
at http://192.168.1.3:8082/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:111339:321 in _createSuperInternal
at node_modules/expo-modules-core/build/errors/CodedError.js:10:8 in constructor
at http://192.168.1.3:8082/node_modules/expo/AppEntry.bundle?platform=ios&dev=true&hot=false&strict=false&minify=false:111384:321 in _createSuperInternal
at node_modules/expo-modules-core/build/errors/UnavailabilityError.js:9:42 in constructor
at node_modules/expo-secure-store/build/SecureStore.js:103:14 in setItemAsync
at node_modules/expo-secure-store/build/SecureStore.js:97:7 in setItemAsync
at src/core/infrastructure/storage/secureStore.ts:4:8 in save
at src/core/infrastructure/storage/secureStore.ts:3:7 in save
at App.tsx:87:4 in login
I don't know what's wrong. Please help.
If anybody is working on a similar issue.
According to this issue
https://github.com/expo/expo/issues/16906
I had to rebuild my application due to expo-dev-client lib I'd being using in order to generate a new artifact. After that I could save my token using the expo-secure-store functions without problem.
I've fixed the error with replacing the expo package with:
https://github.com/react-native-async-storage/async-storage
The other alternatives are:https://reactnative.directory/?search=storage
I am getting the following error screen every time I'm scrolling or navigating the app when I reload my React Native app in iOS Simulator.
enter image description here
I'm not sure what could be the reason for this error.
I thought it could potentially be something wrong with the source of my images but don't think that's the issue.
const UserItem = (props: { onSelect: () => void, user: User }) => {
return <AccountContainer onPress={props.onSelect}>
<AccountImage source={{ uri: props.user.photoUrl }} />
<Text text={props.user.username} />
</AccountContainer>
}
I'm also making sure I strinfiy the json objects as I've seen people had this same issue with AsyncStorage
const save = async <T>(key: string, value: T): Promise<T | null> => {
try {
await AsyncStorage.setItem(key, JSON.stringify(value));
return value;
} catch (error) {
return null;
}
I was able to get the same error by calling AsyncStorage.setItem(null, "#");
You can wrap up the setItem call so it won't throw a native error.
const safeSetStorageItem = (key: string, value: object) => {
if (!key) {
logger.warn("Probably a mistake here...raise a warning and investigate");
return;
}
return await AsyncStorage.setItem(key, JSON.stringify(value));
};
The project is at this Github Repository. The file with the code is at components/Soundboard.js
This code was working previously, but now it looks like the promise is running forever. It looks like neither the resolve function, nor the reject function are executing because if I uncomment all the commented lines below and call the function askForPurchase() the only things printed to the console are
an object that looks like "_40": 0, "_55": {"_40": 0, "_55": null, "_65": 0, "_72": null}, "_65": 3, "_72": null} for the line console.log(RNIap.getPurchaseHistory())
and then the word end.
The buyProduct() function also is no longer initializing an IAP.
const buyProduct = function(){
RNIap.requestPurchase("1985162691", false).then(purchase => {
store.dispatch(setPurchases(purchase))
await RNIap.finishTransaction(purchase, false) //developerPayloadAndroid?: string Should I use this argument? I don't get how to use it
}).catch((error) => {
console.log(error.message);
})
}
const askForPurchase = function(){
if (!store.getState().purchase){
//console.log(RNIap.getPurchaseHistory())
RNIap.getPurchaseHistory().then(purchase => {
//console.log(`test1`)
store.dispatch(setPurchases(purchase))
if (purchase.length == 0){
//console.log(`test if`)
buyProduct()
}else{
//console.log(`test else`)
RNIap.getAvailablePurchases()
}
}, reason => {
console.log(reason)
})
//console.log(`end`)
}
}
EXTRA
This code was working a few months ago and I even pulled a commit(1b9cb81f229680e173ce910892dddedc632c1651, comment: "Made the seal pic more cartoony") from that time to test out. After pulling this commit, I deleted my node_modules and pods, and cleaned my build folder, but the askForPurchase() and buyProduct() functions no longer work in that commit either.
I am testing this on a real iPhone SE running ios 13.6.1
I created a sandbox tester if you need to test it out, but I don't think you'll need it
email: rniapsandbox#gmail.com
pw: Somepassword1
hello #Sam problem is async await problem they are not able to get value because they are not waiting to get data before getting data its firing without data and it was returning promise so you have to use async function
so your code be like
const buyProduct = async()=>{
await RNIap.requestPurchase("1985162691", false).then(purchase => {
store.dispatch(setPurchases(purchase))
await RNIap.finishTransaction(purchase, false) //developerPayloadAndroid?: string Should I use this argument? I don't get how to use it
}).catch((error) => {
console.log(error.message);
})}
const askForPurchase = async()=>{
if (!store.getState().purchase){
//console.log(await RNIap.getPurchaseHistory())
await RNIap.getPurchaseHistory().then(purchase => {
//console.log(`test1`)
store.dispatch(setPurchases(purchase))
if (purchase.length == 0){
//console.log(`test if`)
buyProduct()
}else{
//console.log(`test else`)
RNIap.getAvailablePurchases()
}
}, reason => {
console.log(reason)
})
//console.log(`end`)
}}
You will need to change from
console.log(RNIap.getPurchaseHistory())
to
console.log(await RNIap.getPurchaseHistory())
I want to capture the responsebody in Newman.
const newman = require('newman');
newman.run({
collection: require('./xxx.json'),
iterationData: './data.jsp',
reporters: 'cli'
}, function (err, summary) {
if (err) { throw err; }
console.log('collection run complete!');
console.log(summary);
});
I use the code above. it works fine but I want to capture the json output here from the call. How can I achieve it?
Perhaps you used a wrong term for retrieving json response body. If you want to just get the response body you need to parse JSON returned and to save it to a variable.
If you would use newman to run through command line there are everything is super simple:
let body = JSON.parse(responseBody)
console.log(body)
and after test where you need to see the response you put this 2 lines of code.
But with your case perhaps you need that:
1) Callback option
const newman = require('newman');
newman.run({
collection: require('./xxx.json'),
iterationData: './data.jsp',
reporters: 'cli'
}, function (err, summary) {
if (err) { throw err; }
console.log('collection run complete!');
console.log(summary);
})
.on('request', function (err, data) {
// err, data can be used to write to files using the node fs module.
});
or the better and modern option:
let response = await newman.run({
collection: 'collection',
environment: 'env',
})
.on('request', async function (err, data) {
// err, data can be used to write to files using the node fs module.
});
console.log(response)
Not sure I will be working as expected, but at least try.
Btw, where do you run these tests? just in clear env or use some runner framework.
Postman return execution summary in Callback function. after execution if you save the summary in callback and return it. you can access request/response/ headers.
function runcollection(callback){
newman.run({
collection: 'C:\\newman\\PMP Dependency latest collection\\Updated\\TestCollection.postman_collection.json',
environment: 'C:\\newman\\PMP Dependency latest collection\\Updated\\Test.postman_environment.json',
iterationCount :1
},function(error, summary){
callback(summary)
});
}
runcollection(result => {console.log(result.run.executions[0].response.stream.toString())});
I use my postgres database query to determine my next action. And I need to wait for the results before I can execute the next line of code. Now my conn.query returns a Future but I can't manage to get it async when I place my code in another function.
main() {
// get the database connection string from the settings.ini in the project root folder
db = getdb();
geturl().then((String url) => print(url));
}
Future geturl() {
connect(db).then((conn) {
conn.query("select trim(url) from crawler.crawls where content IS NULL").toList()
.then((result) { return result[0].toString(); })
.catchError((err) => print('Query error: $err'))
.whenComplete(() {
conn.close();
});
});
}
I just want geturl() to wait for the returned value but whatever I do; it fires immediately. Can anyone point me a of a piece of the docs that explains what I am missing here?
You're not actually returning a Future in geturl currently. You have to actually return the Futures that you use:
Future geturl() {
return connect(db).then((conn) {
return conn.query("select trim(url) from crawler.crawls where content IS NULL").toList()
.then((result) { return result[0].toString(); })
.catchError((err) => print('Query error: $err'))
.whenComplete(() {
conn.close();
});
});
}
To elaborate on John's comment, here's how you'd implement this using async/await. (The async/await feature was added in Dart 1.9)
main() async {
try {
var url = await getUrl();
print(url);
} on Exception catch (ex) {
print('Query error: $ex');
}
}
Future getUrl() async {
// get the database connection string from the settings.ini in the project root folder
db = getdb();
var conn = await connect(db);
try {
var sql = "select trim(url) from crawler.crawls where content IS NULL";
var result = await conn.query(sql).toList();
return result[0].toString();
} finally {
conn.close();
}
}
I prefer, in scenarios with multiple-chained futures (hopefully soon a thing of the past once await comes out), to use a Completer. It works like this:
Future geturl() {
final c = new Completer(); // declare a completer.
connect(db).then((conn) {
conn.query("select trim(url) from crawler.crawls where content IS NULL").toList()
.then((result) {
c.complete(result[0].toString()); // use the completer to return the result instead
})
.catchError((err) => print('Query error: $err'))
.whenComplete(() {
conn.close();
});
});
return c.future; // return the future to the completer instead
}
To answer your 'where are the docs' question: https://www.dartlang.org/docs/tutorials/futures/
You said that you were trying to get your geturl() function to 'wait for the returned value'. A function that returns a Future (as in the example in the previous answer) will execute and return immediately, it will not wait. In fact that is precisely what Futures are for, to avoid code doing nothing or 'blocking' while waiting for data to arrive or an external process to finish.
The key thing to understand is that when the interpreter gets to a call to then() or 'catchError()' on a Future, it does not execute the code inside, it puts it aside to be executed later when the future 'completes', and then just keeps right on executing any following code.
In other words, when using Futures in Dart you are setting up chunks of code that will be executed non-linearly.