节点7.6异步等待返回数据的问题 [英] node 7.6 async await issues with returning data

查看:34
本文介绍了节点7.6异步等待返回数据的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于async/await功能,我正在为服务器使用简单的TCP客户端,并且正在使用最新的节点7.6.我是节点和异步编码的新手,因此,如果这很简单,我深表歉意.

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 apologize if this is stupidly easy.

我想运行一个函数,该函数使用特定的参数调用callServer()函数,等它完成获取数据后,再将数据作为变量返回.

I want to run a function that calls the callServer() function with specific parameters, wait until it finishes getting the data, and return the data as a variable.

这是我的代码:

'use strict'
const net = require('net')

var formattedJson = funcRequestToJson("Server.GetStatus", false)

doThings()

async function doThings() {
    var info = await callServer()
}

async function callServer() {
    var client = new net.Socket()

    client.connect(1705, '192.168.28.16', () => {
        console.log('connected to server')
        client.write(formattedJson)
    })

    client.on('data', (data) => {
        client.destroy()
        //return await data
        console.log(data.toString())
    })

    client.on('close', () => {
    })
}

// method and paramBool are always required
// macAddress, paramKey, paramValue are required for if paramBool is true
function funcRequestToJson(method, paramBool, macAddress, paramKey, paramValue) {
    var objectRequest = {}

    objectRequest[ "jsonrpc" ] = "2.0"
    objectRequest[ "method" ] = method
    objectRequest[ "id" ] = 0
    if (paramBool == true) {
        objectRequest[ "params" ] = {
            "client": macAddress,
            [paramKey]: paramValue
        }
    }

    var json = (JSON.stringify(objectRequest) + '\r\n')

    return json
}

所以我没有将objectRequest()声明为异步,因为它没有在服务器上等待,但是我认为callServer()应该是异步的,对不对?我知道可以通过promises来完成,但是我想使用async/await,这似乎是正确的.

So I didn't declare objectRequest() as async because it's not waiting on the server, but I think callServer() should be async, right? I know this can be done with promises, but I wanted to use async/await and this seems to be right.

现在,我想返回来自callServer()和client.on('data',(data)内部的数据,但我似乎无法弄清楚如何异步进行操作.d是制作异步函数并像我尝试的那样用await调用它的一种方法(await返回数据),但是它永远无法正常工作.

Now, I want to return the data that comes from inside callServer() and client.on('data', (data) but I can't seem to figure out how to do it asynchronously. I would think there'd be a way to make an async function and call it with await like I tried (await return data) but it never works right.

很抱歉,这令人费解,但过去一周我一直在研究异步节点教程,但仍然陷于困境.

I'm sorry if this is terribly convoluted, but I've been poring over async node tutorials for the past week and am still stuck.

谢谢!

推荐答案

Async/Await依赖使用对诺言进行异步操作的代码.因此,您需要从任何异步操作中返回一个Promise,以便将其与async/await一起使用.

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.

因此, callServer()需要返回一个承诺,该承诺在其内部的异步操作完成后将得到解决.实际上,只有在该函数返回promise的情况下,您才可以等待该函数中的异步操作. await 使您不必在promise上编写 .then()处理程序,但是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.

以下是如何使 callServer()返回承诺的示例:

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);

    });
}

样品用量:

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


仅向您展示await在做什么,在ES5中(不使用async/await),示例用法如下:


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
});

因此, await 只是让您避免编写 .then()处理程序.在代码的内部执行过程中,只有一个承诺,解释器将为此设置一个 .then()处理程序,以便其知道何时可以解决该承诺.这是语法糖,并不是异步操作真正的魔咒.您仍然必须对所有异步操作使用Promise.您可以使用 await 而不是 .then(),即使您的内幕代码实际上是相同的,您的代码也会显示出更多顺序.

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.

人们认为 await 允许人们像异步代码一样编写异步代码,但实际情况并非如此,尤其是当您处理错误并了解并发问题时.它看起来更加同步,但实际上并没有比ES5中的 .then()更加同步.

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.

此外,请注意错误处理.在人们寻求编写看似同步的代码的过程中,人们似乎完全忘记了在异步操作中处理被拒绝的承诺(使用await时通过try/catch进行处理).我个人还不相信ES6在错误处理方面是向前迈进的一步,因为早期迹象表明ES6似乎鼓励人们忘记错误处理或变得懒惰而不去做,而使用 .then()只是知道在某个地方应该有一个 .catch()才能使它成为可靠的代码.也许这只是一个学习过程,但是当人们使用 await 时,这似乎是一个早期问题.

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.

这篇关于节点7.6异步等待返回数据的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆