node.js - 获取 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))
非常感谢任何关于这些事情如何工作的解决方案或解释/见解,非常感谢异步和承诺的菜鸟
解决方案
获取是异步执行的,您只能在回调中访问结果。在这里,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))
推荐阅读
- c# - 计算不同行和不同列的持续时间?
- html - 使用 VBA 和 HTML 单击自动完成列表中的项目
- javascript - 将google sheet json数据读入chartjs
- javascript - Foreach循环仅在画布图表中显示最后一条记录,而php json不能在javascript中使用
- hyperledger-fabric - rpc 错误 - 当对等方加入 Fabric 中的通道时,提案失败
- java - 线程“main”中的异常 java.lang.NoClassDefFoundError: gherkin/formatter/Formatter Cucumber 5.2.0
- spring-security - CookieCsrfTokenRepository 允许客户端创建自己的 Csrf Tokens
- presto - Presto 因类型不匹配错误而失败
- node.js - 如何全局卸载一个 npm 包 commitizen?
- mongodb - prisma config connect mongodb 不要使用管理员用户