等待从其他地方调用的函数的结果
Waiting for the result of a function called from somewhere else
我有一个节点服务器,我想在其中集成 Paypal。我有一个模块应该 return 来自 paypal 的访问令牌。这个模块有一个异步函数,看起来像这样:
let token: string | null = null;
export async function getToken() {
if (token === null) {
token = await requestTokenFromPaypal()
}
return token;
}
export function resetToken() { token = null }
main:
getToken()
getToken()
getToken()
// -> I want all calls to wait until the first request for the token is finished and then resolve to the token
// -> Currently the token will be requested three times
如果其他请求产生 401 且令牌无效,则调用 resetToken 函数。所以需要一个新的令牌。但是现在每次调用 getToken 都会产生一个令牌请求,直到第一个请求完成并保存到令牌。
那么如何等待从不同代码段调用的另一个函数的结果呢?我已经考虑过保留承诺或类似的东西,但我无法理解它。
我也尝试 google 它但只得到标准的异步代码问题。如果您发现其他类似问题,请参考我。
只是 return 一个承诺,然后 .then
它。
let token: string | null = null;
export async function getToken() {
if (token === null) {
return requestTokenFromPaypal() // this function should return a promise
/* (node-fetch would be the easiest way to do that, but whatever works) */
}
return Promise.resolve(token);
}
export function resetToken() { token = null }
//later, somewhere else in your code
getToken().then(function(token) {
//do something with 'token'
});
您可以检查令牌请求是否已经开始,而不是检查令牌是否可用。
您可以通过检查 tokenPromise 来做到这一点,它基本上只是令牌的包装器。
let tokenPromise = null
export async function getToken() {
if (!tokenPromise) {
tokenPromise = requestTokenFromPaypal()
}
return tokenPromise
}
export function resetToken() { tokenPromise = null }
如果您想知道,直接返回 tokenPromise 而不等待它实际上与等待它然后返回令牌具有相同的效果。
我有一个节点服务器,我想在其中集成 Paypal。我有一个模块应该 return 来自 paypal 的访问令牌。这个模块有一个异步函数,看起来像这样:
let token: string | null = null;
export async function getToken() {
if (token === null) {
token = await requestTokenFromPaypal()
}
return token;
}
export function resetToken() { token = null }
main:
getToken()
getToken()
getToken()
// -> I want all calls to wait until the first request for the token is finished and then resolve to the token
// -> Currently the token will be requested three times
如果其他请求产生 401 且令牌无效,则调用 resetToken 函数。所以需要一个新的令牌。但是现在每次调用 getToken 都会产生一个令牌请求,直到第一个请求完成并保存到令牌。
那么如何等待从不同代码段调用的另一个函数的结果呢?我已经考虑过保留承诺或类似的东西,但我无法理解它。
我也尝试 google 它但只得到标准的异步代码问题。如果您发现其他类似问题,请参考我。
只是 return 一个承诺,然后 .then
它。
let token: string | null = null;
export async function getToken() {
if (token === null) {
return requestTokenFromPaypal() // this function should return a promise
/* (node-fetch would be the easiest way to do that, but whatever works) */
}
return Promise.resolve(token);
}
export function resetToken() { token = null }
//later, somewhere else in your code
getToken().then(function(token) {
//do something with 'token'
});
您可以检查令牌请求是否已经开始,而不是检查令牌是否可用。
您可以通过检查 tokenPromise 来做到这一点,它基本上只是令牌的包装器。
let tokenPromise = null
export async function getToken() {
if (!tokenPromise) {
tokenPromise = requestTokenFromPaypal()
}
return tokenPromise
}
export function resetToken() { tokenPromise = null }
如果您想知道,直接返回 tokenPromise 而不等待它实际上与等待它然后返回令牌具有相同的效果。