【发布时间】: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))
非常感谢任何关于这些事情如何工作的解决方案或解释/见解,非常感谢异步和承诺的菜鸟
【问题讨论】: