我有一個類getter,我只想在事件偵聽器完成時才返回一個值。 有沒有辦法做到這一點?在返回之前等待NodeJS中的事件完成
我知道,我可以許諾把它包起來,並將其應用到鏈,但它不遵循模塊化我需要的應用程序的使用情況:
class Request{
get body(){
console.log('processed before')
console.log(processed)
this._request.on('data', chunk => {
console.log('data received');
if (null == this._body._text) {
this._body._text = "";
}
this._body._text += chunk;
})
.once('end',() => {
console.log('processed')
processed = true;
});
console.log('processed after')
console.log(processed)
console.log('return this._body')
return this._body;
}
}
let req = new Request();
console.log(req.body());
我需要的回報只有在請求「結束」事件發生後繼續並返回。
提前感謝您。
你可以包裹在一個承諾或回調將是的路要走 – marvel308
這是什麼目的this._body._text =「」;'?如果'data'事件被多次調用,'this._body._text'將在每個事件中設置爲空字符串'「」',是嗎? – guest271314
哎呀,很好。意味着要在這一個周圍進行空檢查。 –