gpt4 book ai didi

javascript - 成功将 `this` 上下文传递给异步函数,但是如何在完成 NodeJS 时检索 `this` 上下文?

转载 作者:行者123 更新时间:2023-11-30 14:01:45 25 4
gpt4 key购买 nike

只要我在事件监听器中,我就可以在我想要的上下文中控制台记录 this。但我似乎无法更新或更改更全局的对象。如何返回值以更新更全局的对象?

我尝试过使用 bind 调用函数,我也认为这可能是一个异步问题并尝试使用 promises 来解决。

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,使它成为一个异步问题。 This guide帮我实现了一个 Promise 来解决这个问题。也用过这个reference帮助语法:

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

关于javascript - 成功将 `this` 上下文传递给异步函数,但是如何在完成 NodeJS 时检索 `this` 上下文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56211784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com