[英]Wpf : webbrowser call async silverlight method synchronously in javascript
[英]Call JavaScript class method synchronously
我正在使用JavaScript構建一個包,它有兩個函數: init
和sendData
。
class Client {
init() {
return axios.post(this.baseUrl).then((response) => {
this.token = response.data.token
})
}
sendData() {
return axios.post(this.baseUrl, {token: this.token})
}
}
需要在sendData
方法之前調用init
方法,因為這會返回一個標記。 有沒有辦法在調用sendData
方法之前等待調用sendData
方法?
您是否需要API的使用者才能執行此操作?
// within an async function
const client = new Client();
await client.init();
await client.sendDate();
// or anywhere just using promises
const client = new Client();
client.init().then(() => client.sendDate());
還是API本身?
// definition
class Client {
async init() {
const response = await axios.post(this.baseUrl);
this.token = response.data.token;
}
async sendData() {
await this.init(); // call init before sending data
return axios.post(this.baseUrl, {token: this.token})
}
}
// usage somewhere in an async function
const client = new Client();
client.sendDate() // calls init, then sends the data
如果令牌沒有改變,可能會刪除冗余調用?
class Client {
async init() {
const response = await axios.post(this.baseUrl);
this.token = response.data.token;
}
async sendData() {
if (!this.token) { // now you'll only call init for missing token
await this.init();
}
return axios.post(this.baseUrl, {token: this.token})
}
}
// usage somewhere in an async function
const client = new Client();
await client.sendDate(); // calls init (only the first time), then sends the data
請注意,promise返回函數本質上是異步的,因此無法以同步方式獲取結果。 但是,我們可以使用async / await編寫異步代碼,使其在語法上看起來(幾乎)與同步版本相同。
異步初始化是工廠模式的一個很好的用例。 而不是在構造類之后進行異步工作,而是在之前執行並保持構造函數同步。 在我看來,執行簡單賦值的同步構造函數具有最少的“氣味”並且是最容易測試的。
class Client {
constructor(baseUrl, token) {
this.baseUrl = baseUrl;
this.token = token;
}
async create(baseUrl) {
const response = await axios.post(baseUrl);
return new Client(baseUrl, response.data.token);
}
async sendData() {
return axios.post(this.baseUrl, {token: this.token})
}
}
...
const client = await Client.create('http://foo.com');
const response = await client.sendData();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.