Error while executing javascript promises - promise

I am getting console error as:Uncaught (in promise) TypeError: Failed to execute 'createObjectURL' on 'URL': Overload resolution failed.
I wish to know where I am going wrong in my concepts..Thanks
const myImage = document.querySelector("img");
const myRequest = new Request('elephant.jpg');
// console.log(myRequest)
fetch(myRequest)
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`)
}
else {
console.log(`no HTTP error, elephant.jpg file is present,Status: ${response.status}`)
myBlob=response.blob();
const objectURL = URL.createObjectURL(myBlob);
myImage.src = URL.createObjectURL(response)
}
})
<h1>Fetch Request example</h1>
<img src="" />

Coding alone will not help you all the time, but also knowing when & how to DEBUG will!
You're very close in getting the desired outcome. Lets go step by step to see what you're missing..
If you log response.blob(), it will return PromiseĀ {<pending>}, means you aren't awaiting for this to complete, the executions proceeds to next line window.URL.createObjectURL(myBlob); where myBlob is still empty.
And this is when async await comes to the rescue.
fetch(myRequest).then(async (response) => {
.. your code
myBlob = await response.blob()
}
And secondly,
the `src` property would need the BLOB to display the image so,
myImage.src = window.URL.createObjectURL(myBlob);
Good luck with promises!
My code:
const myImage = document.querySelector("img");
const myRequest = new Request("elephant.jpeg");
fetch(myRequest).then(async (response) => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
} else {
console.log(
`no HTTP error, elephant.jpg file is present,Status: ${response.status}`
);
myBlob = await response.blob() // ensure this is defined in your file
const objectURL = window.URL.createObjectURL(myBlob);
myImage.src = window.URL.createObjectURL(myBlob);
}
});

Double check to make sure you have the right image url.
As it shows in your code, you need the image in the same folder as your code.

Related

Vonage browser to browser audio call return some error

I am using Laravel, and trying add browser to browser audio calling. I am using Vonage (Tookbox) API for this, but I am getting some error.
here is my code:
async function audioCall() {
var publisher;
var targetElement = 'publisher';
var pubOptions = {publishAudio:true, publishVideo:false};
publisher = OT.initPublisher(targetElement, pubOptions, function(error) {
if (error) {
alert("The client cannot publish.");
} else {
console.log('Publisher initialized.');
}
});
// Setting an audio source to a new MediaStreamTrack
const stream = await OT.getUserMedia({
videoSource: null
});
const [audioSource] = stream.getAudioTracks();
publisher.setAudioSource(audioSource).then(() => console.log('Audio source updated'));
// Cycling through microphone inputs
let audioInputs;
let currentIndex = 0;
OT.getDevices((err, devices) => {
audioInputs = devices.filter((device) => device.kind === 'audioInput');
// Find the right starting index for cycleMicrophone
audioInputs.forEach((device, idx) => {
if (device.label === publisher.getAudioSource().label) {
currentIndex = idx;
}
});
});
const cycleMicrophone = () => {
currentIndex += 1;
let deviceId = audioInputs[currentIndex % audioInputs.length].deviceId;
publisher.setAudioSource(deviceId);
};
}
This code return an error on console:
Uncaught SyntaxError: await is only valid in async functions and the top level bodies of modules
I believe the issue is that you have
device.kind === 'audioInput'
and I'm pretty sure device.kind comes out like 'audioinput' (all lowercase).
examples:
https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo/kind
https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/enumerateDevices#examples
That would make audioInputs empty (try to console.log it to verify) and gives you the error because there is no device.
Try:
device.kind.toLowerCase() === 'audioinput'
Hope it works out.

Get file path in the ondata event

I'm using the ondata event to add data to the formData, but I need the relative file path in there (in case someone uploads a folder, so I can recreate the same structure on the server after upload, e.g /myFolder/fileploaded.jpg)
How does one get _relativePath in the ondata event ?
FilePond.setOptions({
server: {
url: 'http://192.168.0.100',
timeout: 7000,
process: {
url: './process',
ondata: (formData) => {
let fullPath = ''; // Need _relativePath here
formData.append('Hello', 'World');
return formData;
}
},
}
});
Never mind, I didn't see in the docs that there is a more advanced process function:
FilePond.setOptions({
server: {
process:(fieldName, file, metadata, load, error, progress, abort, transfer, options) => {
// fieldName is the name of the input field
// file is the actual file object to send
const formData = new FormData();
formData.append(fieldName, file, file.name);
const request = new XMLHttpRequest();
request.open('POST', 'url-to-api');
// Should call the progress method to update the progress to 100% before calling load
// Setting computable to false switches the loading indicator to infinite mode
request.upload.onprogress = (e) => {
progress(e.lengthComputable, e.loaded, e.total);
};
// Should call the load method when done and pass the returned server file id
// this server file id is then used later on when reverting or restoring a file
// so your server knows which file to return without exposing that info to the client
request.onload = function() {
if (request.status >= 200 && request.status < 300) {
// the load method accepts either a string (id) or an object
load(request.responseText);
}
else {
// Can call the error method if something is wrong, should exit after
error('oh no');
}
};
request.send(formData);
// Should expose an abort method so the request can be cancelled
return {
abort: () => {
// This function is entered if the user has tapped the cancel button
request.abort();
// Let FilePond know the request has been cancelled
abort();
}
};
}
}
});

Failed to launch chrome! spawn ...node_modules/puppeteer/.../chrome ENOENT TROUBLESHOOTING when using Puppeteer

I was trying to build a quick lambda that prints a pdf with a specific url, but I get this error: Failed to launch chrome! spawn ...node_modules/puppeteer/.../chrome ... TROUBLESHOOTING
Methods mentioned here : https://github.com/GoogleChrome/puppeteer/issues/807#issuecomment-366529860 did not help me.
The code I'm using:
const browser = await puppeteer.launch({
headless: true,
executablePath: '../../node_modules/puppeteer/.local-chromium/linux-624487/chrome-linux/chrome',
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
try {
const result = await exports.run(browser);
callback(null, result);
} catch (e) {
callback(e);
}
...
exports.run = async (browser) => {
// implement here
// this is sample
const page = await browser.newPage();
await page.goto('https://www.google.com', {
waitUntil: ['domcontentloaded', 'networkidle0']
});
console.log((await page.content()).slice(0, 500));
await page.type('#lst-ib', 'aaaaa');
// avoid to timeout waitForNavigation() after click()
await Promise.all([
// avoid to
// 'Cannot find context with specified id undefined' for localStorage
page.waitForNavigation(),
page.click('[name=btnK]'),
]);
// cookie and localStorage
await page.setCookie({
name: 'name',
value: 'cookieValue'
});
console.log(await page.cookies());
console.log(await page.evaluate(() => {
localStorage.setItem('name', 'localStorageValue');
return localStorage.getItem('name');
}));
const result = await page.pdf({
path: 'hn.pdf',
format: 'A4'
});
console.log(` typeof : ${typeof result}, pdf: ${result}`);
await page.close();
return 'done';
};
check this path =>
\node_modules\puppeteer.local-chromium\win32-818858\chrome-win
you will notice chrome.exe will not exist, now got back one step =>
*\node_modules\puppeteer.local-chromium*
you will find zip file "chrome-win" extract it and move it int to =>
\node_modules\puppeteer.local-chromium\win32-818858
Now you may check it will work.

Attemp to invoke interface method java.lang.String com.facebook.react.bridge.ReadableMap etc on a null object reference

I'm getting this error after uploading image to firebase storage. I am using
"react-native": "0.55.4",
"react-native-fetch-blob": "^0.10.8",
"react-native-image-picker": "^0.26.10",
"firebase": "^5.0.4",
this is my code for uploading the image.
// Prepare Blob support
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
uploadImage = (uri, imageName, mime = "image/jpg") => {
return new Promise((resolve, reject) => {
const uploadUri =
Platform.OS === "ios" ? uri.replace("file://", "") : uri;
let uploadBlob = null;
const imageRef = db
.storage()
.ref("images/")
.child(imageName);
fs.readFile(uploadUri, "base64")
.then(data => {
return Blob.build(data, { type: `${mime};BASE64` });
})
.then(blob => {
uploadBlob = blob;
alert("blob is " + JSON.stringify(blob));
return imageRef.put(blob, { contentType: mime });
})
.then(() => {
uploadBlob.close();
return imageRef.getDownloadURL();
})
.then(url => {
resolve(url);
})
.catch(error => {
reject(error);
});
});};
Attempt to invoke interface method 'java.lang.String com.facebook.react.bridge.ReadableMap.getString(java.lang.String)' on a null object reference readAsText FileReaderModule.java:43 invoke Method.java invoke JavaMethodWrapper.java:372 invoke JavaModuleWrapper.java:160 run NativeRunnable.java handleCallback Handler.java:790 dispatchMessage Handler.java:99 dispatchMessage MessageQueueThreadHandler.java:29 loop Looper.java:164 run MessageQueueThreadImpl.java:192 run Thread.java:764
I faced the same error. The solution is to do a 'Fetch replacement' as the official documentation explains:
Since we are not implementing FileReader polyfill, you might run into
this error in some cases.
If you're facing this problem with Blob polyfill in Debug Mode, try
replace window.fetch with fetch replacement should fix it.
And:
If you have existing code that uses whatwg-fetch, now you don't have
to change existing code after 0.9.0, just use fetch replacement. The
difference between Official fetch and fetch replacement is that,
official fetch uses WHATWG-fetch js library which wraps XMLHttpRequest
polyfill under the hood, and our implementation simply wraps
RNFetchBlob.fetch.
Basically, you just have to add this to your code, just below your window.Blob = Blob; line:
const Fetch = RNFetchBlob.polyfill.Fetch
// replace built-in fetch
window.fetch = new Fetch({
// enable this option so that the response data conversion handled automatically
auto : true,
// when receiving response data, the module will match its Content-Type header
// with strings in this array. If it contains any one of string in this array,
// the response body will be considered as binary data and the data will be stored
// in file system instead of in memory.
// By default, it only store response data to file system when Content-Type
// contains string `application/octet`.
binaryContentTypes : [
'image/',
'video/',
'audio/',
'foo/',
]
}).build()
Documentation:
https://github.com/wkh237/react-native-fetch-blob/wiki/Trouble-Shooting#failed-to-execute-readastext-on-filereader
I am running into the same problem. It has something to do with the prep statements:
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
The error does not occur if I comment them out.
I have solved this by removing all this package because error still appearing even with fetch replacement I think Is triggered by
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
so I have used the old fashion
const uriToBlob = (uri) => {
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest();
xhr.onload = function () {
resolve(xhr.response);
};
xhr.onerror = function () {
reject(new Error('uriToBlob failed'));
};
xhr.responseType = 'blob';
xhr.open('GET', uri, true);
xhr.send(null);
});
}

Parse Cloud Code Save Issue

I wrote some backend code for a Parse.com mobile app a couple of years ago, and have just been asked to add a feature. However, I found that after a small tweak the code wouldn't succeed. So, I rolled back to the working copy, downloaded, then deployed that back and it wouldn't work either! I wonder if this is a change in the Parse software?
The code is failing at the save method as all the logs are fine until then. The log for the error case shows 'No message provided'. If I don't use the message attribute it just shows '{}', so I presume it's empty. I have put the promise resolution in the error case to stop the job timing out while I debug. One thing I have never understood is why I have to make two Seed objects and piggy-back off one to save correctly. If I did a.save(null,...) it wouldn't work.
Any help would be fantastic. Thanks!
PS: Apologies for the indenting below - it is correct in my file.
function flush() {
//Clear the previous records from the class.
var Seed = Parse.Object.extend("Seeds");
var _ = require("underscore");
var arr = [];
var query = new Parse.Query(Seed);
return query.find().then(function(oldSeeds) {
_.each(oldSeeds, function(oldSeed) {
arr.push(oldSeed.destroy());
});
return Parse.Promise.when(arr);
});
}
Parse.Cloud.job("fetchjson", function(request, status) {
var url = 'someurl';
flush().then(function() { Parse.Cloud.httpRequest({url: url}).then(function(httpResponse){
var Seed = Parse.Object.extend("Seeds");
var jsonobj = JSON.parse(httpResponse.text);
var _ = require("underscore");
var results = [];
// do NOT iterate arrays with `for... in loops`
_.each(jsonobj.seeds, function(s) {
var p = new Parse.Promise();
results.push(p); // Needs to be done here or when() will execute immediately with no promises.
var seed = new Seed();
var a = new Seed(s);
var image_url = a.get("image")
//Get the JSON.
Parse.Cloud.httpRequest({url: image_url}).then(function(response) {
console.log("Fetching image at URL: " + image_url);
//Create a new image object and save, passing ref through promise.
var file = new Parse.File('thumb.jpg', { base64: response.buffer.toString('base64', 0, response.buffer.length) });
return file.save();
}).then(function(thumb) {
console.log("Attaching thumb to object");
//Set image ref as object attribute.
a.set("imageFile", thumb);
console.log("Parsing views into viewsint");
//Save decimal string as int into another attribute.
a.set("viewsInt", parseInt(a.get("views")));
console.log("Parsing description into descriptionarray");
//Save string as array into another attribute.
var dar = new Array(1);
//dar[0] = a.get("description")
a.set("descriptionarray", [a.get("description")]);
}, function(error) {
console.log("Error occurred :(");
}).then(function(){
console.log("Saving object");
//Save the object and resolve the promise so we can stop.
seed.save(a,{
success: function(successData){
console.log(successData);
p.resolve(successData);
},
error: function(error){
console.log(error.message);
p.resolve(error);
}
});
});
});
// .when waits for all promises to be resolved. This is async baby!
Parse.Promise.when(results).then(function(data){
console.log("All objects saved");
status.success("Updated Succesfully");
});
}, function(error) {
//Oh noes :'(
console.error('Request failed with response code ' + httpResponse.status);
status.error("Update Failed");
});
});
});
I changed your code a bit and put some comments to explain:
// DEFINE THESE ON THE TOP. NO NEED TO REPEAT.
var _ = require("underscore");
var Seed = Parse.Object.extend("Seeds");
function flush() {
//Clear the previous records from the class.
var arr = [];
var query = new Parse.Query(Seed);
return query.find().then(function(oldSeeds) {
_.each(oldSeeds, function(oldSeed) {
arr.push(oldSeed.destroy());
});
return Parse.Promise.when(arr);
});
}
Parse.Cloud.job("fetchjson", function(request, status) {
var url = 'someurl';
flush().then(function() {
Parse.Cloud.httpRequest({url: url}).then(function(httpResponse){
var jsonobj = JSON.parse(httpResponse.text);
var results = [];
_.each(jsonobj.seeds, function(s) {
// ONE SEED OBJECT WITH INITIAL SET OF DATA FROM JSON
var seed = new Seed(s);
var image_url = seed.get("image")
// A SERIAL PROMISE FOR EACH SEED
var promise = Parse.Cloud.httpRequest({url: image_url}).then(function(response) {
console.log("Fetching image at URL: " + image_url);
//Create a new image object and save, passing ref through promise.
var file = new Parse.File('thumb.jpg', { base64: response.buffer.toString('base64', 0, response.buffer.length) });
return file.save();
}).then(function(thumb) {
// SETTING MORE PROPERTIES
//Set image ref as object attribute.
console.log("Attaching thumb to object");
seed.set("imageFile", thumb);
//Save decimal string as int into another attribute.
console.log("Parsing views into viewsint");
seed.set("viewsInt", parseInt(seed.get("views")));
//Save string as array into another attribute.
console.log("Parsing description into descriptionarray");
seed.set("descriptionarray", [seed.get("description")]);
// SAVING THE OBJECT
console.log("Saving object");
return seed.save();
});
// PUSH THIS PROMISE TO THE ARRAY TO PERFORM IN PARALLEL
results.push(promise);
});
Parse.Promise.when(results).then(function(data){
console.log("All objects saved");
status.success("Updated Succesfully");
});
}, function(error) {
console.error('Request failed with response code ' + httpResponse.status);
status.error("Update Failed");
});
});
});
Thanks knshn. I had refactored the code a lot since that version (including several of the changes you made), but I had posted the version that was identical to that which was working fine before. Your changes let me see the right error. For some reason doing the simple single object implementation didn't work for me originally, hence the nasty workaround. It works now though.
I have now found the culprit - the Seed class had an attribute called 'id'. With the old version this worked fine, but when I deployed that code now it gave an error 101: 'object not found for update'. This must be because the new Parse code is mixing that up with the internal objectId and getting confused that the id is different to what it expects. I wonder how that could still work with the rollback though. Perhaps the at version was tagged to use the older Parse code.
My fix was to use a different name for the id - 'seed_id'.

Resources