Interview question: how to solve asynchronous problem with JQ without ES6 old project?


We all know that ES6 provides promise asynchronous writing, but most companies write it by JQ. How can we use JQ to write the same writing method as promise asynchronous? There are not many people who know this. Let’s write about it

be careful:
Above 1 JQ 1.5
2 key API: $. Deferred ()

<!DOCTYPE html>
    <meta charset="UTF-8">
    <p>deferred test</p>

    <script type="text/javascript">
        // var wait = function () {
        //     var task = function () {
        //          console.log ('execution complete')
        //     }
        //     setTimeout(task, 2000)
        // }
        // wait()

        //Packaged (employee a)
        function waitHandle() {
            var dtd = $.Deferred()
            var wait = function (dtd) {
                var task = function () {
                    console.log ('execution complete')
                    // dtd.reject()
                setTimeout(task, 1000)
                //Wait return
                return dtd.promise()
            //Final return
            return wait(dtd)

        //Use (employee b)
        Var w = waithandle() // promise object
        $.when(w).then(function () {
            console.log('ok 1')
        }, function () {
            console.log('err 1')


In fact, the predecessor of promise is JQ’s deffered. After encapsulation, the usage is almost the same, and ES6 normalizes it

Recommended Today

Build parametric insurance smart contract through chainlink prediction organization

Blockchain technology has unique attributes and can be used to create innovative decentralized insurance products, bringing many benefits to insurance suppliers and customers. In this technical tutorial, we will show you: Main characteristics of decentralized parametric insurance contract Why does chainlink Oracle play an important role in these new insurance products Advantages of using chainlink […]