Pattern for wrapping an Asynchronous JavaScript function to make it synchronous

前端 未结 7 1398
迷失自我
迷失自我 2020-12-09 04:33

I\'m working with a JavaScript API where most of the functions are asynchronous. The API is the WebKit JavaScript Database API which is a binding to a subset of functionali

相关标签:
7条回答
  • 2020-12-09 04:45

    if you are using jQuery Ajax : $.ajax()

    you can set the attribute of asynch to false , and then you will have a synch ajax request to the server.

    0 讨论(0)
  • 2020-12-09 04:47

    Sorry, JavaScript does not provide the language primitives (eg. threads or coroutines) to make asynchronous things act synchronously or vice-versa.

    You generally* get one thread of execution only, so you can't get a callback from a timer or XMLHttpRequest readystatechange until the stack of calls leading to the creation of the request has completely unravelled.

    So in short, you can't really do it; the approach with nested closures on the WebKit page you linked is the only way I know of to make the code readable in this situation.

    *: except in some obscure situations which wouldn't help you and are generally considered bugs

    0 讨论(0)
  • 2020-12-09 04:47

    StratifiedJS allows you to do exactly that.

    There's even an article on how to apply it on browser storage: http://onilabs.com/blog/stratifying-asynchronous-storage

    And this is the Stratified JavaScript library it uses https://gist.github.com/613526

    The example goes like:

    var db = require("webdatabase").openDatabase("CandyDB", ...);
    try {
      var kids = db.executeSql("SELECT * FROM kids").rows;
      db.executeSql("INSERT INTO kids (name) VALUES (:name);", [kids[0]]);
      alert("done");
    } catch(e) {
      alert("something went wrong");
    }
    

    maybe a bit late, but the tech didn't exist back then ;)

    0 讨论(0)
  • 2020-12-09 04:50

    You can try something like:

    function synch()
    {
        var done = false;
        var returnVal = undefined;
    
        // asynch takes a callback method
        // that is called when done
        asynch(function(data) {
            returnVal = data;
            done = true;
        });
    
        while (done == false) {};
        return returnVal;
    }
    

    But that may freeze your browser for the duration of the asynch method...

    Or take a look at Narrative JavaScript: Narrative JavaScript is a small extension to the JavaScript language that enables blocking capabilities for asynchronous event callbacks. This makes asynchronous code refreshingly readable and comprehensible.

    http://neilmix.com/narrativejs/doc/index.html

    Mike

    0 讨论(0)
  • 2020-12-09 04:51

    I am not sure if this is the right place but I cam here searching for answers to making an synchronous calls in Firefox. the solution would be to remove onreadystatechange callback and do a direct call. This is what I had found and my solution synchronous call back with rest service

    0 讨论(0)
  • 2020-12-09 05:00

    This doesn't actually implement synchronous operation of the db query, but this was my solution for easy management. Basically use the calling function as the callback function, and test for the results argument. If the function receives results, it parses them, if not, it sends itself as a callback to the query method.

     render: function(queryResults){
      if (typeof queryResults != 'undefined'){
       console.log('Query completed!');
       //do what you will with the results (check for query errors here)
    
      } else {
       console.log('Beginning query...');
       this.db.read(this.render); //db.read is my wrapper method for the sql db, and I'm sending this render method as the callback.
      }
     }
    
    0 讨论(0)
提交回复
热议问题