![](/img/trans.png)
[英]How can I get type checking for a value passed into my ajax done function through the context?
[英]Successfully passed `this` context to an async function but how to retrieve `this` context when it is done NodeJS?
我能夠控制台登錄this
在我想只要我在事件偵聽器的上下文。 但是我似乎無法更新或更改更具全局性的對象。 如何返回值以更新更全局的對象?
我嘗試用bind調用函數,我也認為這可能是一個異步問題,並嘗試使用Promise解決。
const { createReadStream } = require("fs");
const { createInterface } = require("readline");
export default class Process {
constructor() {
let self = this;
let file = [];
let lineReader = createInterface({
input: createReadStream(this.filePath)
});
lineReader
.on("line", line => {
file.push(line);
})
.on("close", () => {
self.file = file;
console.log(self);
return self;
});
}
console.log(this);
}
}
我希望輸出為:
Process {
filePath: 'path/to/file',
file:
[ 'line1',
'line2'
] }
實際輸出為:
Process {
filePath: 'path/to/file' }
答案是, createInterface
方法返回一個使這成為異步問題的承諾。 本指南幫助我實現了解決該問題的Promise
。 還使用此參考來幫助語法:
const { createReadStream } = require("fs");
const { createInterface } = require("readline");
function processFile(filePath) {
let data = '';
return new Promise((resolve, reject) => {
createInterface({
input: createReadStream(filePath)
})
.on("line", line => {
data += line + '\n';
})
.on("close", f => {
resolve(data)
})
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.