获取 API 并将变量设置为 res

Fetching API and setting a variable to the res

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 来暂停代码,直到承诺 returned 然后到 console.log 正文,但它需要是一个异步函数。有谁知道我是怎么做的可以在继续下面的代码之前为 let 主体分配一个新值吗?或者有办法从 .then 到 return 吗?

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

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))

非常感谢任何关于这些东西如何工作的解决方案或explanations/insights,非常感谢异步和承诺

提取是异步执行的,您只能在回调中访问结果。 这里,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))

您正在使用 promise 从您的 URL https://api.ashx?stopId=${stopId} 中获取数据。由于这需要时间并且是异步的(非阻塞的),因此在获取数据时代码将移动到 console.log(body) 并打印前一个主体 (body = { a: 1 };)。因为代码流在 promise 执行之前移动到 console.log,所以这个 promise 需要时间来获取数据。所以你必须在 then 本身内 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;
    }
  };