Wal*_*ley 6 javascript synchronous async-await node-fetch
我正在尝试将node-fetch与nodejs结合使用以对我的个人api进行api调用。我希望能够在此期间定期同步更新某些值,因为在后台我的数据库会进行更新/更改。我知道异步和等待的存在,但我所有的谷歌搜索,我仍然不太了解它们或它们如何与获取请求交互。
这是我尝试开始工作的一些示例代码,但仍然只是未定义的日志
const fetch = require('node-fetch');
const url = 'http://example.com';
let logs;
example();
console.log(logs);
async function example(){
//Do things here
logs = await retrieveLogs();
//Do more things here
}
async function retrieveLogs(){
await fetch(url)
.then(res => res.json())
.then(json => {return json})
.catch(e => console.log(e))
}
Run Code Online (Sandbox Code Playgroud)
我认为您需要返回类似以下内容的retrieveLogs函数结果:
async function retrieveLogs(){
return await fetch(url)
.then(res => res.json())
}
Run Code Online (Sandbox Code Playgroud)
正如 Ali Torki 在评论中所说,fetch()它是一个异步函数,无论如何都不能“同步”。如果您必须与 HTTP 同步获取(例如,因为您必须在不能异步的属性 getter 中使用它),那么您必须使用不同的 HTTP 客户端,句号。
| 归档时间: |
|
| 查看次数: |
5764 次 |
| 最近记录: |