【发布时间】:2019-02-08 07:01:18
【问题描述】:
我正在尝试使用 node-fetch 和 nodejs 对我的个人 api 进行 api 调用。我希望能够在其中定期同步更新某些值,因为在幕后我的数据库会更新/更改。我知道存在 async 和 await ,但是通过谷歌搜索,我仍然不太了解它们或它们如何与 fetch 请求交互。
这是我正在尝试使用的一些示例代码,但仍然只是未定义的日志
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))
}
【问题讨论】:
-
await example(); -
.then(json => {return json})这行毫无意义。只需将其删除。 -
感谢您的帮助!这两件事都有些正确,但不是全部答案,因为我仍然需要像 Ali 指出的那样返回 fetch
-
请注意,使用
async和await确实不会使您的操作同步。它只是语法糖,可以使您的代码更优雅并像同步一样显示它。动作在幕后仍然是异步的。
标签: javascript async-await synchronous node-fetch