Fetch API 总是返回一个 promise [英] Fetch API always returning a promise

查看:74
本文介绍了Fetch API 总是返回一个 promise的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码在其中调用 api

<预><代码>const fetchToken = async() =>{const response = await axios.post("http://localhost:3000/api/getRedisData",{关键:process.env.AUTH_TOKEN_NAME!,});控制台日志(响应);//这将返回我期望它返回的内容返回响应;};

然后我像这样调用函数.

<预><代码>fetchToken();

现在,这个功能工作得很好.但是当我尝试像下面这样保存这个响应的数据时.

<预><代码>token = fetchToken().then((r) => r);

它返回一个承诺并且它永远不会解决.发生了什么以及我如何等到这个承诺解决.我只需要等待并获取数据.提前致谢.

我更新了这个问题.

假设我有以下对象.

 const authMachine = createMachine({id:身份验证",initial: "unauthenticated",//我想根据令牌改变这个值语境: {//},状态: {//},});

现在我想根据是否获得令牌来更新初始属性.现在我正在做这样的事情.

 首字母:令牌?已认证":未经认证"

所以这里有什么问题?

解决方案

所有 async 函数都返回一个 promise.因此,您的 fetchToken() 函数将始终返回一个承诺.该承诺的解析值将是您从 fetchToken() 函数体返回的任何值.

因此,fetchToken() 的调用者必须使用 await.then() 来获取解析值.async/await 没有免费的午餐.它仍然是异步的.await 在函数内部提供类似同步的行为,而不是在函数外部.

再解释一下.当 fetchToken() 执行时,一旦它遇到第一个 await,它会立即暂停函数体的进一步执行,然后立即将未解析的 promise 返回给调用者.然后调用者继续执行,调用者必须使用 .then()await 来知道 fetchToken() 的主体何时实际上是done 以及它的最终返回值是什么.

然后,稍后,您在 fetchToken() 内部使用的 await 承诺将解析或拒绝,当 JS 解释器返回到事件循环时,然后它将在 await 之后继续执行 fetchToken() 的其余部分.当它最终到达函数体的末尾或遇到 return 语句时,它会解析先前返回的 Promise 以及使用 await.then() 将收到通知,它已完成,并将获得最终返回值作为该承诺的已解析值.然后调用者可以处理该最终值并执行其操作.

因此,您可能希望使用这样的方法来获取最终值或错误:

fetchToken().then(token => {控制台日志(令牌);//这里使用令牌值}).catch(err => {控制台日志(错误);});//此处不能使用令牌值

如果对 fetchToken() 本身的调用在一个 async 函数中,那么它也可以使用 await :

尝试{让令牌 = 等待 fetchToken();控制台日志(令牌);//这里使用令牌值} 抓住(错误){控制台日志(错误);}

I have the following code where I am calling an 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;
    };

Then I am calling the function like this.


    fetchToken();

Now, this function works just fine. But when I try to save the data of this response like the following.


    token = fetchToken().then((r) => r);

It returns a promise and it never resolves. What is happening and how do I wait until this promise resolves. I just need to wait and get the data. Thanks in advance.

I updated this question.

Let's suppose I have the following object.

    const authMachine = createMachine<toggleAuth>({
      id: "auth",
      initial: "unauthenticated", // I want to chage this value based on token
      context: {
        //
      },
      states: {
        //
      },
    });

Now I want to update the initial property based on if I am getting a token or not. Right now I am doing something like this.

    initial: token ? "authenticated" : "unauthenticated"

So what's wrong here?

解决方案

All async functions return a promise. So your fetchToken() function will always return a promise. The resolved value of that promise will be whatever value you return from the fetchToken() function body.

So, the caller of fetchToken() has to use await or .then() to get that resolved value. There is no free lunch with async/await. It's still asynchronous. await gives you synchronous-like behavior inside the function, but not outside the function.

To explain a little further. As fetchToken() executes, as soon as it hits the first await, it immediately suspends further execution of the function body and then immediately returns an unresolved promise back to the caller. The caller then continues to execute and the caller has to use .then() or await to know when the body of fetchToken() is actually done and what its final returned value is.

Then, sometime later, the promises you used await on inside of fetchToken() will resolve or reject and when the JS interpreter is back to the event loop, then it will continue executing the rest of the body of fetchToken() after the await. When it finally gets to the end of the function body or encounters a return statement, then it resolves the promise that was previously returned and the caller that is using either await or .then() will get notified that it is done and will be given the final return value as the resolved value of that promise. The caller can then process that final value and do its thing.

So, you probably want to be using something like this to get the final value or the error:

fetchToken().then(token => {
    console.log(token);
    // use the token value here
}).catch(err => {
    console.log(err);
});
// you cannot use the token value here

If the call to fetchToken() itself is inside an async function, then it can use await also:

try {
    let token = await fetchToken();
    console.log(token);
    // use the token value here
} catch(err) {
    console.log(err);
}

这篇关于Fetch API 总是返回一个 promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆