Я довольно новичок в Node и решил преобразовать одну из моих баз кода в async / await.Преобразование обратных вызовов в Async / await было относительно простым процессом, но я столкнулся с проблемой, когда я храню обратный вызов в очереди.
this.on("request", (requestString, response) => {
// Check if there are no available workers
if (this.freeWorkers.length === 0) {
logger.info("Workers are busy please wait...");
this.queue.push([requestString, response]);
} else {
const worker = this.freeWorkers.pop();
/* Run the worker and send back the response */
worker.run(requestString, response, data => {
response(data);
});
}
});
Проблема, с которой я сталкиваюсь, заключается в том, что я не хочу выходить из асинхронного / ожидающего использования нового Promise (разрешить, отклонить), если мне не нужно.Вышеприведенная версия работает хорошо, потому что другое событие «возврат» завершит сохраненный обратный вызов, когда есть запрос в this.queue.Асинхронная версия выглядит следующим образом:
async request (requestString) {
if (this.freeWorkers.length === 0) {
logger.info("Workers are busy please wait...");
this.queue.push([requestString, /* How do I store the promise here? */]);
} else {
logger.info("sending request...");
const worker = this.freeWorkers.pop();
/* Run the worker and send back the response */
return await worker.run(requestString);
}
}
Вопрос в том, как изнутри функции асинхронности / ожидания можно сохранить обещание в this.queue ()?
Редактировать: Добавление некоторых дополнительных деталей в соответствии с просьбой, чтобы, надеюсь, устранить некоторую путаницу.
«API», если можно так назвать его, из древнего программного обеспечения IBM от 1982 года, которое моя компания использует для внутреннего использования.this.on("request"
испускается из другого класса в моем API.Если вам интересно, вот как сейчас выглядит работник:
/**
* Class Worker is a simple class with only a constructor and 1 run method
* sends a plain TCP request
* Uses a callback response and closes the connection
* */
class Worker {
/**
* Sets variables that it will use in the future
*
* @param {number} port
* @param {TracsRequest} eventEmitter
* */
constructor(port, eventEmitter) {
this.host = /* redacted */;
this.port = port;
this.emitter = eventEmitter;
this.lastRequest = null;
this.lastResponse = null;
}
/**
* Takes in a formatted request string and opens a TCP Port to parse the request
*
* @param requestString
* @param response
*/
async run(requestString) {
this.lastRequest = requestString;
this.lastResponse = response;
const socket = new net.Socket();
let tempBuffer = null;
const client = socket.connect(
this.port,
this.host,
() => {
client.write(requestString);
}
);
let socketPromise = new Promise((resolve, reject) => {
/**************************
* SOCKET EVENT LISTENERS *
**************************/
// store the incoming data
client.on("data", data => {
tempBuffer += data;
});
// client has finished respond with the data
client.on("end", () => {
logger.info("the client has finished");
this.emitter.emit("return", this);
client.destroy();
tempBuffer = tempBuffer.substring(4);
resolve(tempBuffer);
});
// Client has responded with an error send the worker back to the Request class
client.on("error", error => {
logger.error(`OHH snap he's dead Jim:${error}`);
reject(error);
});
});
return await socketPromise;
}
} `