2 回答

TA貢獻1752條經驗 獲得超4個贊
JavaScript 是一種同步、阻塞、單線程的語言。這只是意味著一次只能進行一項操作。
嘗試使用回調函數
class fetchDemo{
constructor(dummy){
this.dummy=dummy;
this.alienMsg(function(data) {
console.log(data);
});
}
alienMsg(callback){
fetch('./file.txt')
.then(response => callback(response.text()))
.then(body =>{
callback(body);
})
.then((txt)=>{
callback(txt);
});
}
}
new fetchDemo(null);

TA貢獻1784條經驗 獲得超9個贊
經過不斷嘗試,我暫時使用 JavaScript 承諾解決了這個問題
但是我不會將我的答案標記為正確
注意:我不得不放棄使用 JavaScript 類
var alienMsg = new Promise(
(res,rej)=>{
fetch('./file.txt')
.then(response => response.text())
.then(body =>{
//console.log(body);
return body;
})
.then((txt)=>{
//returning inside then using JavaScript promises resolve
res(txt)
});
}
);
(()=>{
alienMsg
.then(data=> console.log(data));
})();
添加回答
舉報