gpt4 book ai didi

c# - 如何实现模式 promise /延迟?

转载 作者:IT王子 更新时间:2023-10-29 04:08:52 33 4
gpt4 key购买 nike

我想写一个模式 Promise/Deffered。最终的完美变体是:

MyObject().CallMethodReturningPromise()
.done( result => {
...something doing;
} )
.fail( error => {
...error handle;
} )
.always( () => {
...some code;
} )

我找到了这个实现 https://bitbucket.org/mattkotsenas/c-promises/overviewhttps://gist.github.com/cuppster/3612000 .但是我怎样才能用它来解决我的任务呢???

最佳答案

C# 用 Task 解决了这个问题s

任务解决的问题与 JavaScript 中的 promise 解决的问题相同 - 您可以类似地使用它们。但是通常情况下,您不应该这样做。

有几点不同:

  • 任务内置了取消功能。
  • 任务并不总是开始,您可以有任务并稍后开始。
  • promise 执行同化,你不能有 Promise<Promise<T>>但您可以在 C# 中完成一项任务,并且可能需要调用 .Unwrap在任务上。
  • 在 C# 附带的 TPL(任务并行化库)中有一个规范的任务实现,但在 JavaScript 中有许多 promises 实现。

使用任务

以下是如何将它们与 async/await 一起使用语法 - 将在 ES7 中添加到 JavaScript 中,并可在 ES6 中使用 yield在一些图书馆。

async Task Foo(){
try{
var res = await myObject.CallMethodReturningTaskOrAsyncMethod();
doSomethingWithResponse(res);
} catch(e){
// handle errors, this will be called if the async task errors
} finally {
// this is your .always
}
}

您也可以use .ContinueWith .then 平行但它在 C# 中很少见,并且在可以使用 await 时通常不受欢迎。您可以了解更多关于 using async / await here 的信息.

Defereds 映射到 TaskCompletionSource实例和 PromiseTask在 C# 中。 Task.WhenAll在你使用 $.when 的地方使用或 Promise.all .

你通常写的地方:

a().then(function(res){
return b(res, "foo");
}).then(function(res2){
// do work on res2
});

您将在 C# 中执行以下操作:

var res = await a();
var res2 = await b(res, "foo");
// do work on res2.

关于c# - 如何实现模式 promise /延迟?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26136389/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com