i'm trying to save a base64 image to mobile phone. in expo-media-library i get an unhandled promise error and it does not save image to gallery.
const handleLongPress = async () => {
console.log(qrName);
qrSVG.toDataURL((data) => {
setImageSource("data:image/png;base64," + data);
console.log("DATA: ", imageSource);
});
const base64Code = imageSource.split("data:image/png;base64,")[1];
const filename = FileSystem.documentDirectory + qrName + ".png";
await FileSystem.writeAsStringAsync(filename, base64Code, {
encoding: FileSystem.EncodingType.Base64,
});
const mediaResult = await MediaLibrary.saveToLibraryAsync(filename);
console.log("Result: ", mediaResult);
};
FileSystem.writeasync() works correctly but when it's in the MediaLibrary.saveToLibraryAsync() it sends an unhandled promise error. Here is the Error:
[Unhandled promise rejection: Error: Could not create asset.]at node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:106:50 in promiseMethodWrapper
at node_modules\expo-modules-core\build\NativeModulesProxy.native.js:15:23 in moduleName.methodInfo.name
at node_modules\expo-media-library\build\MediaLibrary.js:164:7 in saveToLibraryAsync
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:294:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:155:27 in invoke
at node_modules\regenerator-runtime\runtime.js:190:16 in PromiseImpl$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:45:6 in tryCallTwo
at node_modules\react-native\node_modules\promise\setimmediate\core.js:200:22 in doResolve
at node_modules\react-native\node_modules\promise\setimmediate\core.js:66:11 in Promise
at node_modules\regenerator-runtime\runtime.js:189:15 in callInvokeWithMethodAndArg
at node_modules\regenerator-runtime\runtime.js:212:38 in enqueue
at node_modules\regenerator-runtime\runtime.js:239:8 in exports.async
at node_modules\expo-media-library\build\MediaLibrary.js:141:7 in createAssetAsync
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:294:29 in invoke
at node_modules\regenerator-runtime\runtime.js:63:36 in tryCatch
at node_modules\regenerator-runtime\runtime.js:155:27 in invoke
at node_modules\regenerator-runtime\runtime.js:165:18 in PromiseImpl.resolve.then$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:37:13 in tryCallOne
at node_modules\react-native\node_modules\promise\setimmediate\core.js:123:24 in setImmediate$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:248:12 in _allocateCallback$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:112:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:166:14 in _callReactNativeMicrotasksPass
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:418:41 in callReactNativeMicrotasks
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:393:6 in __callReactNativeMicrotasks
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:135:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:370:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:134:4 in flushedQueue
const handleLongPress = async () => {
const qrImagesDirectory = FileSystem.documentDirectory + "qrImages/";
const fileName = qrName + ".png";
saveQRAsImage(qrImagesDirectory, fileName, imageSource);
};
const saveQRAsImage = async (qrImagesDirectory, fileName, imageSource) => {
//Get folder
const folder = await FileSystem.getInfoAsync(qrImagesDirectory);
// Check if folder does not exist, create one furthermore
if (!folder.exists) {
await FileSystem.makeDirectoryAsync(qrImagesDirectory);
}
// Write file into the source of program
await FileSystem.writeAsStringAsync(
qrImagesDirectory + fileName,
imageSource,
{
encoding: FileSystem.EncodingType.Base64,
}
);
const ans = await FileSystem.getInfoAsync(qrImagesDirectory + fileName);
// Make the file accessible through mobile phone
FileSystem.getContentUriAsync(ans.uri).then((cUri) => {
//Open save image options
IntentLauncher.startActivityAsync("android.intent.action.VIEW", {
data: cUri,
flags: 1,
});
});
};
this worked for me!
Related
I am generating pdf file with expo-print library, after that I want to save it to gallery or download it to gallery without creating any extra album in user's device.
Below is the code for my Invoice App:
import { shareAsync } from "expo-sharing";
import * as MediaLibrary from 'expo-media-library';
import * as Print from 'expo-print';
const printToPdf = async () => {
let html = PdfCode(company, customer, products); // PDF code is working
try {
const { uri } = await Print.printToFileAsync({ html })
//Taking device permission
const perms = await MediaLibrary.requestPermissionsAsync();
if (perms.granted) {
await MediaLibrary.saveToLibraryAsync(uri); // <- ERROR here, code stops here and break
console.log("Saved to media library"); // <- Not printed in console.
}
await shareAsync(uri, { UTI: '.pdf', mimeType: 'application/pdf' });
} catch (error) {
console.log(error);
}
}
I have marked a comment where I am getting the issue in the code. I have tried MediaLibrary.createAssestSync() but I am getting same error, the full error log is mentioned below:
Error:
Could not create asset.
at node_modules\react-native\Libraries\BatchedBridge\NativeModules.js:104:50 in promiseMethodWrapper
at node_modules\expo-modules-core\build\NativeModulesProxy.native.js:27:27 in moduleName.methodInfo.name
at node_modules\expo-media-library\build\MediaLibrary.js:168:17 in saveToLibraryAsync
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:86:13 in tryCatch
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:66:31 in <anonymous>
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:86:13 in tryCatch
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:124:27 in invoke
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:148:16 in PromiseImpl$argument_0
at node_modules\react-native\node_modules\promise\setimmediate\core.js:45:6 in tryCallTwo
at node_modules\react-native\node_modules\promise\setimmediate\core.js:200:22 in doResolve
at node_modules\react-native\node_modules\promise\setimmediate\core.js:66:11 in Promise
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:147:15 in callInvokeWithMethodAndArg
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:152:154 in _invoke
at node_modules\#babel\runtime\helpers\regeneratorRuntime.js:238:57 in exports.async
at node_modules\expo-media-library\build\MediaLibrary.js:164:7 in saveToLibraryAsync
I am trying to add data to my firestore collection via firebase cloud functions. However, when executing the function the following error appears.
My cloud function code is:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
const Firestore = require("#google-cloud/firestore");
const PROJECTID = "[...]";
const firestore = new Firestore({
projectId: PROJECTID,
timestampsInSnapshots: true,
});
exports.createNewChat = functions.region("europe-west1")
.https.onRequest((request, response) => {
console.log("!!!!!!");
console.log("THe BodY: " + request);
console.log("THe BodY: " + request.rawBody);
console.log("THe BodY: " + request.body);
try {
const groupName = request.body.groupName;
const members: string[] = request.body.members;
firestore.collection("chats").add({
groupName: groupName,
members: members,
lastMessage: new Date(),
messages: [],
}).then((doc: any) => {
const chatId = doc.id;
members.forEach((member) => {
firestore.collection("myChats/" + member).add({
chatKey: chatId,
});
});
return response.status(200).send(doc);
});
} catch (e) {
functions.logger.log("catch clause " + e);
response.status(500).send(e);
}
});
My postman request looks like this:
Header: Content-Type -> application/json
Body (raw, json):
{
"groupName": "someGroupName",
"members": [
"123321aklslasl"
]
}
The exception which is thrown is:
! Google API requested!
URL: "https://oauth2.googleapis.com/token"
Be careful, this may be a production service.
(node:23224) UnhandledPromiseRejectionWarning: Error: 7 PERMISSION_DENIED: Permission denied on resource project [...].
at Object.callErrorFromStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\call.js:31:26)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client.js:179:52)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client-interceptors.js:336:141)
at Object.onReceiveStatus (E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\client-interceptors.js:299:181)
at E:\Workspaces\cloudFunctions\functions\node_modules#grpc\grpc-js\build\src\call-stream.js:145:78
at processTicksAndRejections (internal/process/task_queues.js:79:11)
Caused by: Error
at WriteBatch.commit (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\write-batch.js:414:23)
at DocumentReference.create (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\reference.js:291:14)
at CollectionReference.add (E:\Workspaces\cloudFunctions\functions\node_modules#google-cloud\firestore\build\src\reference.js:1967:28)
at E:\Workspaces\cloudFunctions\functions\lib\index.js:39:39
at C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:560:16
at runFunction (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:533:15)
at runHTTPS (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:559:11)
at handler (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\lib\emulator\functionsEmulatorRuntime.js:479:23)
at Layer.handle [as handle_request] (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\XXXXX\AppData\Roaming\npm\node_modules\firebase-tools\node_modules\express\lib\router\route.js:137:13)
(node:23224) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 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(). T
o terminate the node process on unhandled promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:23224) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
In a Cloud Function for Firebase you should use the Admin SDK for Node.js and not the standard JS SDK.
In addition, you need to use Promise.all() to execute in parallel the calls to the asynchronous add() method in the forEach() loop.
So the following set of adaptations should solve your problem:
import * as functions from "firebase-functions";
import * as admin from "firebase-admin";
admin.initializeApp();
exports.createNewChat = functions.region("europe-west1")
.https.onRequest((request, response) => {
const groupName = request.body.groupName;
const members: string[] = request.body.members;
const db = admin.firestore();
db.collection("chats").add({
groupName: groupName,
members: members,
lastMessage: new Date(),
messages: [],
}).then((doc: any) => {
const chatId = doc.id;
const promises = [];
members.forEach((member) => {
promises.push(db.collection("myChats/" + member).add({
chatKey: chatId,
}));
});
return Promise.all(promises);
})
.then(() => {
response.status(200).send(JSON.stringify(doc));
})
.catch(e => {
functions.logger.log("catch clause " + e);
response.status(500).send(JSON.stringify(e));
});
});
So I am trying to set up an Ethereum flashloan script on the Kovan test network, partly because of the great amount of funds needed to execute it on Mainnet.
I have therefore found all the Kovan addresses of the services used (dydx, kyber, the tokens to be exchanged etc.) and made a new key called ‘kovan’ with those addresses within the ‘addresses’ folder.
I then finally succeeded in deploying the contract on Kovan. And the websocket interaction of getting and displaying the blocks also works.
I expect it to be error-free while waiting for a transaction to go through. But every time it receives a new block, it gives me an error saying:
UnhandledPromiseRejectionWarning: Error: call revert exception (method="decimals()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.1)
This is the whole console log:
λ node run-arbitrage.js
{
kyber: { kyberNetworkProxy: '0x692f391bCc85cefCe8C237C01e1f636BbD70EA4D' },
uniswap: { router: '0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D' },
dydx: { solo: '0x4EC3570cADaAEE08Ae384779B0f3A45EF85289DE' },
tokens: {
dai: '0xc4375b7de8af5a38a93548eb8453a498222c4ff2',
usdc: '0xdcfab8057d08634279f8201b55d311c2a67897d2',
weth: '0xd0a1e359811322d97991e03f863a0c30c2cf029c'
}
}
web3-shh package will be deprecated in version 1.3.5 and will no longer be supported.
web3-bzz package will be deprecated in version 1.3.5 and will no longer be supported.
New block received. Block # 24267204
(node:20188) UnhandledPromiseRejectionWarning: Error: call revert exception (method="decimals()", errorSignature=null, errorArgs=[null], reason=null, code=CALL_EXCEPTION, version=abi/5.0.1)
at Logger.makeError (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\logger\lib\index.js:179:21)
at Logger.throwError (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\logger\lib\index.js:188:20)
at Interface.decodeFunctionResult (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\node_modules\#ethersproject\abi\lib\interface.js:286:23)
at Contract.<anonymous> (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:300:56)
at step (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:46:23)
at Object.next (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:27:53)
at fulfilled (C:\Users\Frederik\Rod\m3\node_modules\#ethersproject\contracts\lib\index.js:18:58)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:20188) UnhandledPromiseRejectionWarning: Unhandled promise rejection. 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:20188) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
And this is my run-arbitrage.js file:
require("dotenv").config()
const Web3 = require('web3');
const { ChainId, Token, TokenAmount, Pair } = require('#uniswap/sdk');
const abis = require('./abis');
const { kovan: addresses } = require('./addresses');
console.log(addresses)
const Flashloan = require('./build/contracts/Flashloan.json');
const web3 = new Web3(
new Web3.providers.WebsocketProvider(process.env.INFURA_KOVAN_URL)
);
const { address: admin } = web3.eth.accounts.wallet.add(process.env.PRIVATE_KEY);
const kyber = new web3.eth.Contract(
abis.kyber.kyberNetworkProxy,
addresses.kyber.kyberNetworkProxy
);
const ONE_WEI = web3.utils.toBN(web3.utils.toWei('1'));
const AMOUNT_DAI_WEI = web3.utils.toBN(web3.utils.toWei('20000'));
const DIRECTION = {
KYBER_TO_UNISWAP: 0,
UNISWAP_TO_KYBER: 1
};
const init = async () => {
const networkId = await web3.eth.net.getId();
const flashloan = new web3.eth.Contract(
Flashloan.abi,
Flashloan.networks[networkId].address
);
let ethPrice;
const updateEthPrice = async () => {
const results = await kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
1
)
.call();
ethPrice = web3.utils.toBN('1').mul(web3.utils.toBN(results.expectedRate)).div(ONE_WEI);
}
await updateEthPrice();
setInterval(updateEthPrice, 15000);
web3.eth.subscribe('newBlockHeaders')
.on('data', async block => {
console.log(`New block received. Block # ${block.number}`);
const [dai, weth] = await Promise.all(
[addresses.tokens.dai, addresses.tokens.weth].map(tokenAddress => (
Token.fetchData(
ChainId.MAINNET,
tokenAddress,
)
)));
const daiWeth = await Pair.fetchData(
dai,
weth,
);
const amountsEth = await Promise.all([
kyber
.methods
.getExpectedRate(
addresses.tokens.dai,
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
AMOUNT_DAI_WEI
)
.call(),
daiWeth.getOutputAmount(new TokenAmount(dai, AMOUNT_DAI_WEI)),
]);
const ethFromKyber = AMOUNT_DAI_WEI.mul(web3.utils.toBN(amountsEth[0].expectedRate)).div(ONE_WEI);
const ethFromUniswap = web3.utils.toBN(amountsEth[1][0].raw.toString());
const amountsDai = await Promise.all([
kyber
.methods
.getExpectedRate(
'0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee',
addresses.tokens.dai,
ethFromUniswap.toString()
)
.call(),
daiWeth.getOutputAmount(new TokenAmount(weth, ethFromKyber.toString())),
]);
const daiFromKyber = ethFromUniswap.mul(web3.utils.toBN(amountsDai[0].expectedRate)).div(ONE_WEI);
const daiFromUniswap = web3.utils.toBN(amountsDai[1][0].raw.toString());
console.log(`Kyber -> Uniswap. Dai input / output: ${web3.utils.fromWei(AMOUNT_DAI_WEI.toString())} / ${web3.utils.fromWei(daiFromUniswap.toString())}`);
console.log(`Uniswap -> Kyber. Dai input / output: ${web3.utils.fromWei(AMOUNT_DAI_WEI.toString())} / ${web3.utils.fromWei(daiFromKyber.toString())}`);
if(daiFromUniswap.gt(AMOUNT_DAI_WEI)) {
const tx = flashloan.methods.initiateFlashloan(
addresses.dydx.solo,
addresses.tokens.dai,
AMOUNT_DAI_WEI,
DIRECTION.KYBER_TO_UNISWAP
);
const [gasPrice, gasCost] = await Promise.all([
web3.eth.getGasPrice(),
tx.estimateGas({from: admin}),
]);
const txCost = web3.utils.toBN(gasCost).mul(web3.utils.toBN(gasPrice)).mul(ethPrice);
const profit = daiFromUniswap.sub(AMOUNT_DAI_WEI).sub(txCost);
if(profit > 0) {
console.log('Arb opportunity found Kyber -> Uniswap!');
console.log(`Expected profit: ${web3.utils.fromWei(profit)} Dai`);
const data = tx.encodeABI();
const txData = {
from: admin,
to: flashloan.options.address,
data,
gas: gasCost,
gasPrice
};
const receipt = await web3.eth.sendTransaction(txData);
console.log(`Transaction hash: ${receipt.transactionHash}`);
}
}
if(daiFromKyber.gt(AMOUNT_DAI_WEI)) {
const tx = flashloan.methods.initiateFlashloan(
addresses.dydx.solo,
addresses.tokens.dai,
AMOUNT_DAI_WEI,
DIRECTION.UNISWAP_TO_KYBER
);
const [gasPrice, gasCost] = await Promise.all([
web3.eth.getGasPrice(),
tx.estimateGas({from: admin}),
]);
const txCost = web3.utils.toBN(gasCost).mul(web3.utils.toBN(gasPrice)).mul(ethPrice);
const profit = daiFromKyber.sub(AMOUNT_DAI_WEI).sub(txCost);
if(profit > 0) {
console.log('Arb opportunity found Uniswap -> Kyber!');
console.log(`Expected profit: ${web3.utils.fromWei(profit)} Dai`);
const data = tx.encodeABI();
const txData = {
from: admin,
to: flashloan.options.address,
data,
gas: gasCost,
gasPrice
};
const receipt = await web3.eth.sendTransaction(txData);
console.log(`Transaction hash: ${receipt.transactionHash}`);
}
}
})
.on('error', error => {
console.log(error);
});
}
init();
Im doing conversion of html to pdf function on AWS Lambda using phantom-html-to-pdf package with Nodejs. I had encountered some errors which shows
Cannot read property 'logs' of undefined
I try to comment it and it shows another error which is
Cannot read property 'numberOfPages' of undefined
I'm not sure is it the error of the package or because it won't work on AWS Lambda . Also not sure why all the function inside async is not working.
Here's the code :
const fs = require("fs");
var phantomjs = require("phantomjs");
const conversion = require("phantom-html-to-pdf")({});
exports.handler = (event, context, callback) => {
console.log("Start");
conversion(
{ html: "<h1>Hello World</h1>" },
// eslint-disable-next-line handle-callback-err
async (err, pdf) => {
const output = fs.createWriteStream("output.pdf");
console.log("Process");
console.log(pdf.logs);
console.log(pdf.numberOfPages);
// since pdf.stream is a node.js stream you can use it
// to save the pdf to a file (like in this example) or to
// respond an http request.
pdf.stream.pipe(output);
console.log("Done");
callback(null, "done");
}
);
console.log("End");
};
Here's the error :
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "TypeError: Cannot read property 'logs' of undefined",
"trace": [
"Runtime.UnhandledPromiseRejection: TypeError: Cannot read property 'logs' of undefined",
" at process.on (/var/runtime/index.js:37:15)",
" at process.emit (events.js:198:13)",
" at emitPromiseRejectionWarnings (internal/process/promises.js:140:18)",
" at process._tickCallback (internal/process/next_tick.js:69:34)"
]
}
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "TypeError: Cannot read property 'numberOfPages' of undefined",
"trace": [
"Runtime.UnhandledPromiseRejection: TypeError: Cannot read property 'numberOfPages' of undefined",
" at process.on (/var/runtime/index.js:37:15)",
" at process.emit (events.js:198:13)",
" at emitPromiseRejectionWarnings (internal/process/promises.js:140:18)",
" at process._tickCallback (internal/process/next_tick.js:69:34)"
]
}
{
"errorType": "Runtime.UnhandledPromiseRejection",
"errorMessage": "TypeError: Cannot read property 'stream' of undefined",
"trace": [
"Runtime.UnhandledPromiseRejection: TypeError: Cannot read property 'stream' of undefined",
" at process.on (/var/runtime/index.js:37:15)",
" at process.emit (events.js:198:13)",
" at emitPromiseRejectionWarnings (internal/process/promises.js:140:18)",
" at process._tickCallback (internal/process/next_tick.js:69:34)"
]
}
Update!!!
I tried to change whatever name I want, it works fine. If I delete the pdf, it just wont work. Same issues as previous error. What is actually going on here?
const fs = require("fs");
var AWS = require("aws-sdk");
var phantomjs = require("phantomjs");
const conversion = require("phantom-html-to-pdf")({});
exports.handler = (event, context, callback) => {
console.log("Start");
conversion(
{ html: "<h1>Hello World</h1>" },
// eslint-disable-next-line handle-callback-err
function(err, haha) {
const output = fs.createWriteStream("output.pdf");
console.log("Process");
//console.log(test.logs);
//console.log(test.numberOfPages);
// since pdf.stream is a node.js stream you can use it
// to save the pdf to a file (like in this example) or to
// respond an http request.
haha.stream.pipe(output);
console.log("Done");
callback(null, "done");
}
);
console.log("End");
};
I'm trying to make this code to be synchronous but for some reason async/await doesn't work.. Im working in React-native with two differents modules. I want to see my geolocation in googleMaps but it gets me a error because the asynchronous stuff.
App is the root component, im importing getLocalitation function.
export default class App extends Component {
Appmetod = async () => {
const resp = await getLocalitation();
console.log('Appmetod: latitud: ' + resp.latitude);
Linking.openURL(`http://www.google.com/maps/place/-33.317597,-71.405500`);
}
render() {
return (
<View style={styles.container}>
<Button title="Click me" onPress={this.Appmetod } />
</View>
);
}
}
const getLocalitation = () =>{
console.log('DENTRO DE GetLocalitaion');
const geoOptions={
enableHighAccuracy: true,
timeOut: 10000
};
const coordenates = navigator.geolocation.getCurrentPosition( geoSucces,goFailure, geoOptions);
console.log('DESPUES DE COORDENATES');
return coordenates;
}
const geoSucces = (position) => {
console.log('DENTRO DE GEOSUCCEES');
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const coordenates={
latitude: latitude,
longitude: longitude
};
console.log('COORDENATES: ' + coordenates.latitude);
return coordenates;
}
const goFailure = (err) => {
console.log('Error en al geolocalizar: ' + err);
return null;
}
OUTPUT:
C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Utilities\infoLog.js:16 Running application "geolocation" with appParams: {"rootTag":161}. __DEV__ === true, development-level warning are ON, performance optimizations are OFF
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:2 DENTRO DE GetLocalitaion
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:10 DESPUES DE COORDENATES
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:16 DENTRO DE GEOSUCCEES
C:\Users\jnunez\React-Native\Proyects\geolocation\src\getLocalitation.js:26 COORDENATES: -32.92098393
C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\YellowBox\YellowBox.js:67 Possible Unhandled Promise Rejection (id: 0):
TypeError: Cannot read property 'latitude' of undefined
TypeError: Cannot read property 'latitude' of undefined
at _callee$ (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:1895:58)
at tryCatch (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41538:19)
at Generator.invoke [as _invoke] (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41713:24)
at Generator.prototype.<computed> [as next] (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41581:23)
at tryCatch (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41538:19)
at invoke (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41614:22)
at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:41624:15
at tryCallOne (blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:45254:14)
at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:45355:17
at blob:http://localhost:8081/19d9ce97-42d2-4939-91b8-160b264c9c79:46233:21
console.warn # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\YellowBox\YellowBox.js:67
onUnhandled # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Promise.js:45
onUnhandled # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\promise\setimmediate\rejection-tracking.js:71
(anonymous) # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:256
_callTimer # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:152
callTimers # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\Core\Timers\JSTimers.js:414
__callFunction # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:366
(anonymous) # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:106
__guard # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:314
callFunctionReturnFlushedQueue # C:\Users\jnunez\React-Native\Proyects\geolocation\node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:105
(anonymous) # debuggerWorker.js:80
await / async do not stop code being asynchronous.
They are tools which let you write non-asynchronous style code by managing promises.
You can only await a promise. getLocalitation does not return a promise.
See How do I convert an existing callback API to promises? to get a promise for navigator.geolocation.getCurrentPosition.
It is because you're using await keyword with a function that is not async
const resp = await getLocalitation();
You can either put an async before the () when defining getLocation or you can just remove await from const resp = await getLocalitation(), since you don't need to use await with something that does not return a promise.
In case you want to make getLocalitation async you do it like this
const getLocalitation = async () =>{
console.log('DENTRO DE GetLocalitaion');
const geoOptions={
enableHighAccuracy: true,
timeOut: 10000
};
const coordenates = navigator.geolocation.getCurrentPosition( geoSucces,goFailure, geoOptions);
console.log('DESPUES DE COORDENATES');
return coordenates;
}