1. Home
  2. Docs
  3. Manual
  4. Playbook
  5. Command list
  6. async/await function

async/await function

Qt5 does not support the async/await function in JavaScript. Fortunately, the Promise, Generator, and Yield functions have been provided since Qt5.12. We can use these three functions for special processing to achieve an effect similar to async/await. The following is a simple example.

function assertEqual(x, y) {
    return new Promise(function(resolve, reject) {
        if(x === y) {
            Qt.callLater(resolve, "Yes, it's equal.")
        }else{
            Qt.callLater(reject, "No, it's not equal.")
        }
    });
}


asyncGenerator(function *(){
    for(let i = 0; i < 10; i++) {
        yield assertEqual(x, y).then(function(result){
            Playbook.log("assertResult.then", result)
        }).catch(function(err){
            Playbook.log("assertResult.catch", err)
        })
     }
})()

AsyncGenerator is equivalent to async, while yield is equivalent to await, but the object of yield must be an asynchronous object of Promise, which achieves the effect of async/await.

The asyncGenerator function is provided by the framework and can be directly used by developers. Its specific source code address is:
https://github.com/aoyiduo/woterm/blob/main/woterm/js/async.js,cut as follows:

function asyncGenerator(fn) {
    return function() {
        var thiz = this,
        args = arguments
        return new Promise(function(resolve, reject) {
            var gen = fn.apply(thiz, args)
            function _next(value) {
                step("next", value)
            }
            function _throw(err) {
                step("throw", err)
            }
            function step(key, arg) {
                try {
                    var info = gen[key](arg)
                    var value = info.value
                } catch (error) {
                    reject(error)
                    return
                }
                if(info.done) {
                    resolve(value)
                } else {
                    Promise.resolve(value).then(_next, _throw)
                }
            }
            _next(undefined)
        })
    }
}

Doc navigation