【问题标题】:Can not store the result of a get call using Fetch-node无法使用 Fetch-node 存储 get 调用的结果
【发布时间】:2019-01-31 06:52:25
【问题描述】:

我正在使用 Fetch-node 获取服务。

 const response = await fetch("MY URL", {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000,
      }).then(res => res.json()).then(json => console.log(json));
      console.log(response);

然后我将结果记录在第二个console.log() 中,一切都很好。 但是,当涉及到第二个console.log() 时,响应是未定义的。 我需要的是在响应中存储的第二个记录。

我做的有什么问题吗?

【问题讨论】:

  • 那么不要只记录,而是返回它......
  • @Andreas 你的意思是返回 json?

标签: javascript node.js ajax promise es6-promise


【解决方案1】:

如前所述,您没有返回 response 的值,因此它不会等于任何值。你可以 return 来自最终 then 的 JSON,或者如果你觉得它更干净,只需 await 两者,而不是使用 .then。

const response = await fetch("MY URL", {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
        },
        timeout: 5000
      });

const json = await response.json();

console.log(json);

【讨论】:

    【解决方案2】:

    你应该在你的函数中返回你的值。

    const response = await fetch("MY URL", {
            method: 'GET',
            headers: {
              'Content-Type': 'application/json',
            },
            timeout: 5000,
          }).then(res => res.json()).then(json => { 
             // do something 
             return json  //<--- return a value
            });
          console.log(response);
    

    【讨论】:

      【解决方案3】:

      您可以使用 async/await 编写整个代码。在您的代码中,您混合了 promise 和 async/await 语法,却忘记从最后一个 .then() 函数返回 json。

      这就是我编写代码的方式:

      async function fetchData() {
        const response = await fetch("https://jsonplaceholder.typicode.com/todos/1", {
          method: 'GET',
          headers: {
            'Content-Type': 'application/json',
          },
          timeout: 5000,
        })
        const data = await response.json();
        console.log(data);
      }
      
      fetchData();

      【讨论】:

      • 很有趣,我相信你前几天在另一个问题的 cmets 中给了我一些关于 fetch 的提示,现在我们在这里提交相同的答案:)
      • @TylerRoper 我没有工作......所以在互联网上尝试一切...... :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-12
      • 1970-01-01
      • 2021-04-04
      • 2012-12-11
      • 1970-01-01
      • 2020-02-27
      • 2017-09-28
      相关资源
      最近更新 更多