`git.clone()` returns SyntaxError: await is only valid in async function
nodeselector opened this issue · 6 comments
Please be sure to mention:
- whether you are using Node or the Browser
Node - how you are using it (if you are using a bundler what bundler; if you are using a
<script>tag what CDN URL)
Following the node quickstart tutorial, the below code returns SyntaxError: await is only valid in async function:
const git = require('isomorphic-git');
const fs = require('fs');
const os = require('os');
const path = require('path');
git.plugins.set('fs', fs);
// Make temporary directory
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'test-'));
console.log(dir);
// Behold - it is empty!
fs.readdirSync(dir);
await git.clone({
fs,
dir,
url: 'https://github.com/isomorphic-git/isomorphic-git',
ref: 'master',
singleBranch: true,
depth: 10
});
// Now it should not be empty...
fs.readdirSync(dir);
^^^^^
SyntaxError: await is only valid in async function at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:616:28) at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
It seems per the tutorial and here that we should be able to use await, since .clone() returns a promise.
This is javascript ES6 error, the proper syntax looks like this:
async function foo() {
await git.clone({
fs,
dir,
url: 'https://github.com/isomorphic-git/isomorphic-git',
ref: 'master',
singleBranch: true,
depth: 10
});
}top level await is only available in console developer tools and I think that was proposal to add this to the language but I don't know the status.
if you want top level you need to create async IIFE:
async (() => {
await git.clone({
fs,
dir,
url: 'https://github.com/isomorphic-git/isomorphic-git',
ref: 'master',
singleBranch: true,
depth: 10
});
})();@wmhilton This can be added to docs, not every one will know everything about ES6. I had this problem with jQuery Terminal when the user didn't know that he need to escape \ in string when he create ASCII art. I've added that do getting started guide next to the relevant part about greetings where you put welcome message.
Now that we're at it. Is there a way for git.clone to have a callback?
@millette I know about the proposal it was comment about current implementations. AFAIK browsers don't allow top level await yet, not sure about babel.
Just trying to be helpful by providing the reference. https://v8.dev/features/top-level-await#support links to current browser issues.