我正在写一个Chrome扩展与socket api(虽然这个文档是过时的,API的最新版本是here),我发现该代码是真的很难组织:我该如何优化嵌套函数太多的代码?
所有方法在名称空间chrome.experimental.socket
下,为了简单起见,我只使用socket
。
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 < 0) throw "Send Data Error";
socket.read(socketId, function(readInfo){
if(readInfo.resultCode < 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){
// ............
});
});
});
})
});
})
,因为这两个socket.write
和socket.read
是异步的,我不得不窝回调,以确保下一个请求被发送后,先前的请求得到了正确的响应。
管理这些嵌套函数真的很难,我该如何改进它?
UPDATE
我想有一个方法send
,我可以为使用:
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
});
http://stackoverflow.com/questions/8302218/chrome-tabs-create-function-wrapper-why-doesn-this-work –
@ GRIGORE-TURBODISEL你可能认真吗? – wong2
Yea man,com'on。这就是我从'//在这里阻塞直到上一次发送得到响应'所得到的结果。 –