How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?

后端 未结 14 2286
暗喜
暗喜 2020-11-21 05:07

I have a JavaScript widget which provides standard extension points. One of them is the beforecreate function. It should return false to prevent an

14条回答
  •  后悔当初
    2020-11-21 05:43

    With async: false you get yourself a blocked browser. For a non blocking synchronous solution you can use the following:

    ES6/ECMAScript2015

    With ES6 you can use a generator & the co library:

    beforecreate: function (node, targetNode, type, to) {
        co(function*(){  
            let result = yield jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
            //Just use the result here
        });
    }
    

    ES7

    With ES7 you can just use asyc await:

    beforecreate: function (node, targetNode, type, to) {
        (async function(){
            let result = await jQuery.get('http://example.com/catalog/create/' + targetNode.id + '?name=' + encode(to.inp[0].value));
            //Just use the result here
        })(); 
    }
    

提交回复
热议问题