node 7.6 async await issues with returning data

前端 未结 1 1722
别跟我提以往
别跟我提以往 2020-12-22 14:23

I am working on a simple TCP client for a server and am using the latest node 7.6 because of the async/await functions. I\'m new to node and asynchronous coding, so I apolog

相关标签:
1条回答
  • 2020-12-22 14:50

    Async/Await relies on code that uses promises for async operations. So you need to return a promise from any async operation in order to use it with async/await.

    So, callServer() needs to return a promise that is resolved when the async operation inside it is done. In fact, you can only await an async operation in a function if that function returns a promise. await saves you from having to write .then() handlers on promises, but async/await does not magically know when async operations are done. You still have to wrap them in promises.

    Here's an example of how you could make callServer() return a promise:

    async function callServer(formattedJson) {
        return new Promise((resolve, reject) => {
            let client = new net.Socket()
    
            client.connect(1705, '192.168.28.16', () => {
                console.log('connected to server')
                client.write(formattedJson)
            })
    
            client.on('data', (data) => {
                resolve(data);
                client.destroy()
            })
    
            client.on('close', () => {
            })
    
            client.on('error', reject);
    
        });
    }
    

    Sample Usage:

    try {
        var info = await callServer(funcRequestToJson("Server.GetStatus", false));
    } catch(e) {
        // error here
    }
    

    Just to show you what await is doing, in ES5 (without async/await), the sample usage would be this:

    callServer(funcRequestToJson("Server.GetStatus", false)).then(info => {
        // info is available here
    }).catch(err => {
        // error here
    });
    

    So, await is just letting you avoid writing the .then() handler. Internally in the execution of the code, there's just a promise that the interpreter sets up a .then() handler for so it will know when that promise is resolved. This is syntactical sugar, not really any magic with async operations. You still have to use promises for all your async operations. You can use await instead of .then() and your code will appear more sequential even though it's really the same under the covers.

    People think that await allows one to write asynchronous code as if it was synchronous, but that isn't really the case, especially if you handle errors and understand concurrency issues. It will look more synchronous, but isn't actually any more synchronous than it was with .then() in ES5.

    And, watch out for error handling. In people's quest to write synchronous looking code, people seem to completely forget to handle rejected promises in their async operations (which are handled with try/catch when using await). I'm personally not yet convinced that ES6 is a step forward when it comes to error handling as the early indications are that ES6 seems to encourage people to just forget about error handling or get lazy and not do it, whereas it's easier when using .then() to just know that there should be a .catch() somewhere for it to be solid code. Maybe that's just a learning process, but it seems to be an early issue when people use await.

    0 讨论(0)
提交回复
热议问题