【问题标题】:Fetching API and setting a variable to the res获取 API 并将变量设置为 res
【发布时间】:2021-08-21 05:06:32
【问题描述】:
const fetch = require('node-fetch');
let body = { a: 1 };

const stopId = 413

fetch(`https://api.ashx?stopId=${stopId}`, {
    method: 'post',
    body:    JSON.stringify(body),
    headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => body = json);

console.log(body)

我得到了输出:{ a: 1 } 而不是 API JsonResponse,但是当我使用 .then(json => console.log(json)); 时,我得到了所需的响应..

我尝试使用 await fetch 来暂停代码,直到 promise 返回然后返回到 console.log 主体,但它需要是一个异步函数。有谁知道我之前如何为 let 主体分配一个新值继续下面的代码?或者有没有办法从.then 返回?

所以我可以这样做:(我知道这行不通)

function fetchStop(stopId){
fetch(`https://api.ashx?stopId=${stopId}`, {
   method: 'post',
   body:    JSON.stringify(body),
   headers: { 'Content-Type': 'application/json' },
})
.then(res => res.json())
.then(json => return body);
}

console.log(fetchStop(stopId))

非常感谢任何关于这些事情如何工作的解决方案或解释/见解,非常感谢异步和承诺的菜鸟

【问题讨论】:

    标签: node.js fetch fetch-api


    【解决方案1】:

    获取是异步执行的,您只能在回调中访问结果。 这里,console.log(body) 在发起网络调用后立即执行。

    const fetch = require('node-fetch');
    let body = { a: 1 };
    
    const stopId = 413
    
    fetch(`https://api.ashx?stopId=${stopId}`, {
        method: 'post',
        body:    JSON.stringify(body),
        headers: { 'Content-Type': 'application/json' },
    })
    .then(res => res.json())
    .then(json => body = json);
    
    console.log(body)
    

    要访问结果,

    function fetchStop(stopId){
    return fetch(`https://api.ashx?stopId=${stopId}`, {
       method: 'post',
       body:    JSON.stringify(body),
       headers: { 'Content-Type': 'application/json' },
    })
    .then(res => res.json())
    }
    
    fetchStop(stopId).then(result => console.log(result))
    

    【讨论】:

      【解决方案2】:

      您正在使用 Promise 从您的 URL https://api.ashx?stopId=${stopId} 获取数据。由于这将花费时间并且是异步的(非阻塞),因此在获取数据时代码将移动到 console.log(body) 并打印前一个正文 (body = { a: 1 };)。因为在 promise 执行之前代码流移动到 console.log,所以这个 promise 需要时间来获取数据。因此,您必须在其内部进行 console.log 。因为那是您的承诺稍后执行的时间点。您可以使用 async await 轻松完成此操作

      const yourFunction = async () => {
        const fetch = require('node-fetch');
        let body = { a: 1 };
        
        const stopId = 413;
          const { hostname: location } = window.location;
          const data = {
            method: 'post',
           body:    JSON.stringify(body),
           headers: { 'Content-Type': 'application/json' },
          }
        
          const response = await fetch(`https://api.ashx?stopId=${stopId}`, data);
          if (!response.ok) throw Error(response.message);
        
          try {
            body = await response.json();
            return;
          } catch (err) {
            throw err;
          }
        };

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-14
        • 2014-11-19
        • 1970-01-01
        • 2014-07-21
        • 2012-05-04
        • 2013-11-28
        • 1970-01-01
        相关资源
        最近更新 更多