我有下面的代码,我在其中调用一个api
const fetchToken = async () => {
const response = await axios.post("http://localhost:3000/api/getRedisData",
{
key: process.env.AUTH_TOKEN_NAME!,
});
console.log(response); // this returns what I expect it to return
return response;
};
然后我调用这样的函数。
fetchToken();
现在,这个函数运行得很好。但是当我尝试保存这个响应的数据时,如下所示。
token = fetchToken().then((r) => r);
它回报了一个承诺,却从未解决。发生了什么,我该如何等待这个承诺的实现。我只需要等待并获取数据。提前谢谢。
我更新了这个问题
假设我有以下对象。
const authMachine = createMachine<toggleAuth>({
id: "auth",
initial: "unauthenticated", // I want to chage this value based on token
context: {
//
},
states: {
//
},
});
现在,我想根据是否获得令牌来更新初始属性。现在我正在做这样的事情。
initial: token ? "authenticated" : "unauthenticated"
那么这里出了什么问题?
如果您在async
函数中,您可以只await
它来获取数据。
const token = await fetchToken();
console.log(token);
// do other stuff with token
如果不是,那么您需要使用then
方法中的令牌来完成您想要完成的一切。这是因为您正在调用一个async
方法,而没有能力对其进行await
。执行将继续。then
函数是当async
方法成功完成时发生的回调。
fetchToken().then(token => {
console.log(token)
// do other stuff with token
});
所有async
函数都返回一个promise。因此,您的fetchToken()
函数将始终返回一个promise。该promise的解析值将是从fetchToken()
函数体返回的任何值。
因此,fetchToken()
的调用者必须使用await
或.then()
来获得解析的值。async/await
没有免费午餐。它仍然是异步的。await
在函数内部为您提供类似同步的行为,但在函数外部则不然。
进一步解释。当fetchToken()
执行时,一旦碰到第一个await
,它就会立即暂停函数体的进一步执行,然后立即将未解析的promise返回给调用者。然后调用者继续执行,调用者必须使用.then()
或await
来知道fetchToken()
的主体何时实际完成,以及它的最终返回值是什么
然后,稍后,您在fetchToken()
内部使用await
的promise将解析或拒绝,当JS解释器返回到事件循环时,它将在await
之后继续执行fetchToken()
主体的其余部分。当它最终到达函数体的末尾或遇到return
语句时,它将解析之前返回的promise,并且使用await
或.then()
的调用方将收到完成通知,并将获得最终返回值作为该promise的解析值。然后,调用者可以处理最终值并执行它的操作。
所以,你可能想使用这样的东西来获得最终值或错误:
fetchToken().then(token => {
console.log(token);
// use the token value here
}).catch(err => {
console.log(err);
});
// you cannot use the token value here
如果对fetchToken()
本身的调用在async
函数内部,则它也可以使用await
:
try {
let token = await fetchToken();
console.log(token);
// use the token value here
} catch(err) {
console.log(err);
}