尽管使用了异步/等待,但仍返回了承诺{<pending>}

时间:2020-09-05 17:02:41

标签: javascript

这是我最初的尝试:

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,但我不想仅用它来获取数据。

0 个答案:

没有答案