我想在我的类方法中使用Promises.在Promise反模式中,我读到为每个新函数创建一个新的承诺被认为是坏的.
但是,我不想在我的项目中返回不相关的promise,所以我想做这样的事情:
class MyClass {
async getToken() {
return new Promise(
(resolve, reject) => {
// . . .
const token_str = '<response_from_http_request>';
resolve(token_str);
}
)
}
async doSomething(token) {
return new Promise(
(resolve, reject) => {
const result = // . . .
resolve(result);
}
)
}
async doAnotherSomething(token) {
return new Promise(
(resolve, reject) => {
const result = // . . .
resolve(result);
}
)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我会像这样使用它:
let instance = new MyClass();
(async () …Run Code Online (Sandbox Code Playgroud) 我有以下一段代码:
private void btnAction_Click(object sender, RoutedEventArgs e)
{
/** Clear the results field */
txtResult.Text = "";
/** Disable the button and show waiting status */
btnAction.IsEnabled = false;
lblStatus.Text = "Wait...";
/** Get input from the query field */
string input = query.Text;
/** Run a new task */
Task.Run(() => {
// calling a method that takes a long time (>3s) to finish and return
var attempt = someLibrary.doSomethingWith(input);
// return the result to the GUI thred
this.Dispatcher.Invoke(() …Run Code Online (Sandbox Code Playgroud)