title: How could I optimize this code with too many nest functions?
body: <p>I'm writing a Chrome extension with the <a href="http://code.google.com/chrome/extensions/experimental.socket.html" rel="nofollow">socket api</a>(though this doc is out of date, the latest version of the api is <a href="http://code.google.com/searchframe#OAMlx_jo-ck/src/chrome/common/extensions/api/experimental_socket.idl&amp;type=cs" rel="nofollow">here</a>), and I found that the code is really hard to organize:</p>
  
  <p>All the methods are under the namespace <code>chrome.experimental.socket</code>, I would just use <code>socket</code> below for simplicity. </p>
  
  <pre><code>socket.create("tcp", {}, function(socketInfo){
      var socketId = socketInfo.socketId;
  
      socket.connect(socketId, IP, PORT, function(result){
          if(!result) throw "Connect Error";        
  
          socket.write(socketId, data, function(writeInfo){
              if(writeInfo.bytesWritten &lt; 0) throw "Send Data Error";
  
              socket.read(socketId, function(readInfo){
                  if(readInfo.resultCode &lt; 0) throw "Read Error";
                  var data = readInfo.data; // play with the data
                  // then send the next request
                  socket.write(socketId, data, function(writeInfo){
                      socket.read(socketId, function(readInfo){
                          // ............
                      });
                  });
              });
          })
      });
  })
  </code></pre>
  
  <p>because both <code>socket.write</code> and <code>socket.read</code> are asynchronous, I have to nest the callbacks to make sure that the next request is send after the previous request got the correct response.</p>
  
  <p>it's really hard to manage these nested functions, how could I improve it?</p>
  
  <p><strong>UPDATE</strong></p>
  
  <p>I'd like to have a method <code>send</code> which I can use as:</p>
  
  <pre><code>send(socketId, data, function(response){
      // play with response
  });
  // block here until the previous send get the response
  send(socketId, data, function(response){
      // play with response
  });
  </code></pre>