[英]How to write better async/await + promise code?
So this is how it looks.这就是它的外观。
function async doAction() {
await this.waitForData();
// do some other things after data loads
// when data loads it's available in this.data
}
function waitForData() {
if (!this.promise) {
this.promise = new Promise(res => this.promiseResolve = res);
return this.promise;
}
else {
return Promise.resolve(this.data);
}
}
function loadData(data) {
//some things
this.data = data;
if (this.promiseResolve) {
this.promiseResolve(this.data);
}
}
It works pretty fine, doAction
waits for data load and then action starts.它工作得很好,
doAction
等待数据加载,然后动作开始。 But it's pretty much code, is there a better way to do it?但这几乎是代码,有更好的方法吗?
There's some bugs with concurrent calls or calls in unexpected sequence.并发调用或意外顺序调用存在一些错误。 I would do
我会做
function waitForData() {
if (!this.promise) {
this.promise = new Promise(res => this.promiseResolve = res);
}
return this.promise;
}
function loadData(data) {
//some things
this.data = data;
if (this.promiseResolve) {
this.promiseResolve(this.data);
this.promiseResolve = null;
} else {
this.promise = Promise.resolve(this.data);
}
}
But other than that, yes this is the way to go for connecting two independent things by promises.但除此之外,是的,这是 go 通过承诺连接两个独立事物的方式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.