我有一个方案,其中有一个功能可以检查是否需要userWhiteListing。如果不是,则调用allowUserToLogin函数。如果是,则检查特定用户是否被列入白名单。如果未列入白名单,则抛出错误,否则调用allowUserToLogin函数。
我正在寻找一种更好的承诺方式,而不是异步等待方式。
这里是一个例子。
vholder = @cxxnew vholder()
channelVals = @cxx vholder->get_channel()
jvals = reinterpret(Complex{Float32},
unsafe_wrap(Array, pointer(channelVals), length(channelVals)))
我仍处于学习阶段。有没有更好的方法来使用Promise处理这种情况。
任何帮助将不胜感激。
答案 0 :(得分:0)
在许多情况下,使用异步等待可以清除大量承诺的代码。
public async function sample(): Promise<{ session: string; url: string }> {
if (await this.userWhiteListingRqd() && !(await this.isUserWhiteListed()) {
throw new Error("The user must be whitelisted but is not.");
}
await this.allowUserToLogin();
return { session, url };
}
答案 1 :(得分:0)
如果您不想使用异步/等待,请尝试一下:
function sample(): Promise<{ session: string; url: string }> {
return this.userWhiteListingRqd()
.then((whiteListingRqd) =>
this.isUserWhitelisted().then(
(isUserWhitelisted) => isUserWhitelisted || !whiteListingRqd
)
)
.then((userIsAllowed) =>
userIsAllowed ? this.allowUserToLogin() : Promise.reject(new Error())
)
.then(() => ({ session, url }));
}
警告:像这样的承诺链并不易读。