nodejs에서 비동기에 문제가 있습니다. 다음 코드에서
//Imagine we are inside a function
// many things here before reading a file
this.data_receiver; //want to this get file content
fs.readFile('/data.txt', (err, data) => {
if (err) throw err;
//console.log(data);
this.data_receiver= data; // get data
});
//I want to process data_receiver
......
문제는 파일에서 데이터를 조금씩 가져 와서 일부 변수에 저장 한 다음 해당 변수를 외부에서 사용할 수 있다는 것입니다.
나는이 비동기에 익숙하지 않아 문제가 있습니다.
는 this
콜백 내부 함수에 묶여 있지 않습니다. 다음을 수행해야합니다.
this.data_receiver; //want to this get file content
var me = this;
fs.readFile('/data.txt', (err, data) => {
if (err) throw err;
//console.log(data);
me.data_receiver = data; // get data
});
console.log(this.data_receiver);
또한 이것은 콜백 범위에 관한 것입니다. 기술적으로 말하면 "비동기 함수"이지만 "비동기 함수"를 async
다음과 같은 함수에 연결하는 것이 더 일반적입니다 .
async function foo() {
return Promise.resolve();
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다