0

I'm trying to run Javascript code containing await in Qt's web engine. Here is a minimal example illustrating what I'm trying to do:

QWebEngineView webView;
webView.page()->runJavaScript("await (new Promise(r => setTimeout(r, 100)))");

The problem is that when I run this, I get the following Javascript error (which Qt logs in Qt Creator's console):

js: Uncaught ReferenceError: await is not defined

When I first saw this, I thought it was because Qt Web Engine uses an older version of Chromium that doesn't support await. But using the method from my answer here, I found out that that the version of Chromium it was using was Chromium 80, and according to caniuse, await is supported in Chromium 55 and later, so it should be supported in Chromium 80.

So my question is, why do I get this error even though it's using a version of Chromium that should support await, and how do I fix this?

Donald Duck
  • 8,409
  • 22
  • 75
  • 99
  • await is only defined in a function that is `async` - though there is a flag for top-level await, but the answer below is good – Jaromanda X Sep 25 '20 at 09:29
  • @JaromandaX Do you know how to enable top-level await? I checked [`QWebEngineSettings`](https://doc.qt.io/qt-5/qwebenginesettings.html) but couldn't find anything in there. – Donald Duck Sep 25 '20 at 09:33
  • probably not in the environment you are in – Jaromanda X Sep 25 '20 at 09:47

1 Answers1

1

Try:

webView.page()->runJavaScript("(async () => await (new Promise(r => setTimeout(r, 100))))()");
Veyis Aliyev
  • 313
  • 2
  • 11
  • This works in the example I provided, but in my real code I need to return a value after the `await`, and embedding it in an `async` function returns a `Promise` object instead of the value I need. – Donald Duck Sep 25 '20 at 09:31
  • You can use: `const x = () => new Promise(r => setTimeout(r, 100))` And Then call function in async function as `(async () => { const z = await x(); })` – Veyis Aliyev Sep 25 '20 at 09:38
  • I ended up using `console.log` to pass the output to the C++ code, and I used [this answer](https://stackoverflow.com/a/47983559/4284627) to get that output. – Donald Duck Sep 25 '20 at 12:08