When i run the following program:
JS:
async function write(){
const filehandle = window.showOpenFilePicker();
const writable = await filehandle.createWritable();
await writable.write('The file has been updated');
await writable.close();
}
HTML:
<button onclick = "write();">
write file
</button>
I get the following error:
[Violation] Avoid using document.write(). https://developers.google.com/web/updates/2016/08/removing-document-write
I clicked the link and it was no help, and i got the same error when using document.append, even though document.write was not used.
I'm still a newbie to the File System Access API, and need help. Thank you all!
Edit: i have found out that naming a function 'write' is enough to trigger the document.write detection, but even after renaming the function, i now get the error:
Uncaught (in promise) TypeError: filehandle.createWritable is not a function
The window.showOpenFilePicker() method returns a promise with an array of file handles according to the docs:
This means you should fulfill the promise (using await or chaining it with a then:
async function write(){
const filehandle = await window.showOpenFilePicker();
// rest of code...
}
Other than that, showOpenFilePicker returns an array containing the file handles. It needs to be retrieved from the array before you can create a writable. You can use array destructuring to do exactly that:
async function write(){
const [filehandle] = await window.showOpenFilePicker();
const writable = await filehandle.createWritable();
await writable.write('The file has been updated');
await writable.close();
}
And that should do the trick.
Related
I have the following code from Twilio to access local camera on browser :
async function ShowLocalVideo() {
Twilio.Video.createLocalVideoTrack().then(track => {
const localMediaContainer = document.getElementById('LocalMedia');
localMediaContainer.appendChild(track.attach());
});
}
I would like to make sure the user Granted Access to the camera before continuing the execution of other steps. Or at least he responded. So I'm calling
await ShowLocalVideo();
alert('Hi !');
But alert Hi ! is trigerred before the browser says : This file wants to use your camera.
Is is possible to make sure the code doesn't continue until the user responds to This file wants to use your camera. ?
Thanks,
Cheers
You're mixing async/await syntax with using Promise .then.
Since you're not awaiting on the result of createLocalVideoTrack().then(...), the async function will return early. You can correct this by replacing .then with await the following way:
async function ShowLocalVideo() {
const track = await Twilio.Video.createLocalVideoTrack();
const localMediaContainer = document.getElementById('LocalMedia');
localMediaContainer.appendChild(track.attach());
}
Alternatively, you can await on the result of createLocalVideoTrack().then(...), but that would mix the styles and create confusion.
So currently I'm working on a web application that uses a model I built previously. I have the file stored locally in my github repository and I'm trying to retrieve that model and load it into a variable as so
<script src="https://cdn.jsdelivr.net/npm/#tensorflow/tfjs#2.0.0/dist/tf.min.js"></script>
<script>
const model = await tf.loadLayersModel('https://foo.bar/tfjs_artifacts/model.json');
</script>
The first script tag should load in the tensorflow.js library (https://www.tensorflow.org/js/tutorials/setup).
The error that appears in the terminal is
Uncaught SyntaxError: await is only valid in async function
Am I missing something with the tensorflow.js implementation? Or am I missing something with the await keyword in the model assignment?
Your issue is that you are using the using the await keyword outside of an async function. Async functions are special functions that allow the word await, which makes it so the program waits for the function to finish running.
A solution to this would be
async function tensorFlow(){
const model = await tf.loadLayersModel('https://foo.bar/tfjs_artifacts/model.json');
}
tensorFlow()
or you can use the .then() function.
tf.loadLayersModel('https://foo.bar/tfjs_artifacts/model.json').then(model => {
};
I use this
async function run(){
....
}
( async() =>{
await run()
})()
I have used async for with great success in handling output streams from processes with node.js, but I'm struggling to get something that I was hoping could "just work" with the browser fetch API.
This works great to async'ly handle chunks of output streaming from a process:
for await (const out of proc.child.stdout) {
...
}
(in an async function context here of course)
I tried to do something similar in a browser where I want to gain access to the data while it is being sent to me from the server.
for await (const chunk of (await fetch('/data.jsonl')).body) {
console.log('got', chunk);
}
This does not work in Chrome (Uncaught TypeError: (intermediate value).body is not async iterable).
For my use case this is not necessary, so I am simply using let data = await (await fetch(datapath)).text(); in my client code for now. This is analogous to the typical use of .json() instead of .text() on the awaited fetch, so no processing can begin until the entire response is received by the browser. This is not ideal for obvious reasons.
I was looking at Oboe.js (I think the relevant impl is somewhere near here) which pretty much deals with this but its internals are fairly ugly so it looks like that might be the only way to do this for now?
If async iteration isn't implemented (meaning async for cannot be used yet) isn't there another way to use the ReadableStream in a practical way?
Unfortunately async iterable support is not yet implemented, despite being in the spec. Instead you can manually iterate, as shown in this example from the spec. (I'll convert examples to async/await for you in this answer.)
const reader = response.body.getReader();
const { value, done } = await reader.read();
if (done) {
console.log("The stream was already closed!");
} else {
console.log(value);
}
You can use recursion or a loop to do this repeatedly, as in this other example:
async function readAllChunks(readableStream) {
const reader = readableStream.getReader();
const chunks = [];
let done, value;
while (!done) {
({ value, done } = await reader.read());
if (done) {
return chunks;
}
chunks.push(value);
}
}
console.log(await readAllChunks(response.body));
According to the spec, a ReadableStream such as the fetch-API's Response.body does have a getIterator method. For some reason it's not async-iterable itself, you explicitly have to call that method:
const response = await fetch('/data.json');
if (!response.ok)
throw new Error(await response.text());
for await (const chunk of response.body.getIterator()) {
console.log('got', chunk);
}
I believe the current state of affairs in mid 2020 is that async for does not work on the fetch body yet.
https://github.com/whatwg/streams/issues/778 This issue appears to have tracking bugs for browsers and none of them have the functionality implemented yet.
I don't currently know of another way to make use of the .body ReadableStream provided by fetch.
The standard way to do the task implicit in the question is to use a websocket.
I write the following code to read the data from the file and push into array. But attachments.length is printing 0 first and then data is loaded and print.
const fs=require('fs');
const util=require('util');
const files=['t1.csv','t2.csv','t3.csv'];
async getdata(){
const read=util.promisify(fs.readFile);
let attachments = [];
async function run(file){
let data=await read(file);
attachments.push(data);
}
for(let file of files){
await run(file);
}
console.log(attachments.length);//should print 3
}
How to load the data first and then push correctly.
Edit: change the some part of code to use await. But loop break after first iteration without giving any error neither print my attchments.length .
Edit 2: problem resolved. Calling function should also need to be await. Thanks every one.
This is happening because run() should be awaited as well in this case,
see async function
One approach is using IIFE:
(async file => {
let data = await read(file);
console.log(data);
attachments.push(data);
})('/home/nadeem/Desktop/test.csv')
When you call an async function, it returns a promise that will eventually resolve with the value returned by the function (or reject with an uncaught exception thrown from within the function).
So you're trying to log the number of attachments before the run () function has finished. Here's what you need:
run('/home/nadeem/Desktop/test.csv')
.then(() => console.log(attachments.length))
I am using the following in my angular app:
let getName = greenlet( async username => {
let url = `https://api.github.com/users/${username}`
let res = await fetch(url)
let profile = await res.json()
return profile.name
})
console.log(await getName('developit'));
Angular seems to be changing this 'await' into 'yield':
How do i use this within my Angular5 application? Thanks.
Babel changes async/await in the browser into generator functions, which utilize the yield keyword. Yields only work when they are in the correct context; specifically the next stage will be ensuring that the yield appears inside a generator function (you can read more about generators, but basically they are identified by a * in the function signature, e.g. function *doSomething().
A generator function will not get created if you have not correctly managed your async keywords. Babel will convert that await into a generator, but because the outer function is not async, it won't create the generator wrapper, thus the error. Some IDEs will report this error before you compile, but that's what the error you are seeing means.
You mentioned that this console.log is sitting inside the ngOnInit lifecycle hook; that function call is not by itself asynchronous. You can decorate it with async, but I wouldn't recommend that (it works, but what does it actually mean?). Instead you can try calling an explicitly async function and just ignore the returned promise:
ngOnInit() {
this.someFunction();
}
async someFunction() {
console.log(await getName('developit'));
}
We'll assume for now that greenlet knows what to do with the async function it has been handed (does it resolve the promise?)