جافا سكريبت - كيف تنشئ عميل TCP في NodeJS باستخدام async/await؟


لقد كتبت عميل TCP التالي في Node.js.

const net = require('net');

const HOST = 'linux345';
const PORT = 2345;
let ErrCode = 1;

const client = new net.Socket();

client.connect(PORT, HOST, function() {
    ErrCode = 0;
});

client.on('data', function(data) {    
    console.log('Client received: ' + data);
     if (data.toString().endsWith('exit')) {
       client.destroy();
    }
});

client.on('close', function() {
});

client.on('error', function(err) {
    ErrCode = err.code;
    console.log(ErrCode);
});

console.log(ErrCode);

يرجى اقتراح كيفية كتابة نفس المنطق باستخدام async/await

لقد اطلعت على المنشور التالي لكنه غير مفيد. مشاكل node 7.6 مع async await في إرجاع البيانات

الإجابة رقم 1

هناك حزمة مذهلة تغلف مأخذ التوصيل Node الأصلي داخل وعد. مما يتيح لك استخدام صياغة async/await على جميع طرق المأخذ.

يمكن العثور على الحزمة على NPM.

مثال

import net from "net"
import PromiseSocket from "promise-socket"

const socket = new net.Socket()

const promiseSocket = new PromiseSocket(socket)

await connect(80, "localhost")
// or
await connect({port: 80, host: "localhost"})