首页 > 解决方案 > 获取 API 并将变量设置为 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 来暂停代码,直到 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.jsfetchfetch-api

解决方案


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

推荐阅读