我想取得Route裡面的list
使用下面物件
1.這樣的使用方式會把Route.refreshRoute綁定上去的then蓋掉嗎??
2.這樣的使用方式妥當嗎?還是會推薦什麼其他比較好的用法
var r = new Route() ;
//這邊想要監聽r.status的Promise完成了沒
r.status.then(function(){
//Do what i want.
}) ;
class Route
{
constructor()
{
this.status = null ;
this.list = null ;
this.refreshRoute() ;
}
// 07/05 15:00 >> 新增這個function
//還是用這種方式取會比較好??
//但就是很不希望寫到後面全部都要有async...
async getRoute()
{
await this.status ;
return this.list ;
}
refreshRoute()
{
var that = this ;
//這裡的doGet回傳Promise
this.status = Request.doGet() ;
this.status.then(rs => {
that.list = rs ;
})
return this ;
}
}
你原本的寫法應該會報錯吧
然後不知道為什麼要透過 status 來賦值給 list
這樣的寫法不知道是你要的嗎
class Route {
constructor() {
this.status = null ;
this.list = null ;
this.init = async() => {
await this.refreshRoute();
return this;
}
}
async refreshRoute() {
this.list = await doGet();
}
}
const doGet = () => {
return new Promise((resolve) => setTimeout(() => resolve('myList'), 3000));
}
const r = new Route() ;
r.init().then((myRoute) => {
console.log(myRoute.list);
});
感謝~剛剛被一些邏輯卡住了QQ
可以再簡化為
class Route {
constructor() {
this.list = null;
}
async refreshRoute() {
this.list = await doGet();
}
}
const doGet = () => {
return new Promise((resolve) => setTimeout(() => resolve('myList'), 3000));
}
(async () => {
const r = new Route();
await r.refreshRoute();
console.log( r.list );
})();
另外,在實際應用上,還要加上[錯誤處理]。
marlin12感謝~