这是我最初的尝试:
const fetch = require('node-fetch');
...
const getUserData = async function() {
return await fetch('http://jsonplaceholder.typicode.com/users');
}
const usersStore = getUserData();
console.log(usersStore)
我得到结果:Promise { <pending> }
对于仍然有Promise感到困惑,我尝试了以下方法:
const usersStore = getUserData()
.then(res => res.json())
.then(json => json);
但是得到了相同的结果,所以我尝试了:
const getUserData = function() {
const url = 'http://jsonplaceholder.typicode.com/users';
return new Promise((resolve, reject) => {
const result = fetch(url)
.then(response => response.json)
.then((json) => json);
return resolve(result);
});
}
结果还是一样。
唯一有效的方法是IIFE,但我不想仅用它来获取数据。