获取 API 并将变量设置到 res

问题描述 投票:0回答:2
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))

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

javascript fetch-api
2个回答
0
投票

获取是异步执行的,您只能在回调中访问结果。 在这里,

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

0
投票

您正在使用 Promise 从您的 URL 获取数据

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

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;
    }
  };

© www.soinside.com 2019 - 2024. All rights reserved.