How to wait on asynchronous javascript function wi

2019-08-30 00:20发布

This is something related to porting from Qt Webkit to Qt Webengine. The following code works well in webkit.

<script type="text/javascript">
  var result = objectExposedFromC++.someFunction(); //sync;
  console.log("I want to use result here");
</script>

But things changed in webengine.

<script type="text/javascript">
  var result = objectExposedFromC++.someFunction(); //async;
  console.log("I want to use result here, but result isn't avaiable");
</script>

One way to make it work is shown as following.

<script type="text/javascript">
  var result = objectExposedFromC++.someFunction(function(returnValue){// callback after async return;
    console.log("I can use returnValue now.");
  }); //async
  //other code execute before callback;
</script>

But the js code are tens of thouands of, and old browser client won't work once change. I just want to make async call to sync call.

Things become better when I found async/await in ES7, but it isn't a solution.

<script type="text/javascript">
  (async function(){
    //async_fucntion will call objectExposedFromC++.someFunction() finally;
    var result = await async_fucntion();
    console.log("I can use returnValue now.");
  })()
</script>

<script type="text/javascript">
  (async function(){
      //other js code that call async fucntion too.
  })()
</script>

```

As you can see,

(1)I must make all my js code async which was sync, leading order scripts out of order.

(2)old browser client based on qt webkit won't work either, because it might not support async/await.

So, how to wait on asynchronous javascript function without async/await support? With that I can

(1) need not to change any existing js code. Browser client can inject new js code to change async fucntion behaviors.

(2) new browser client and old browser client work simutaneously.

Any tips are welcome. Thanks in advance.

0条回答
登录 后发表回答