【问题标题】:Training on promise and await / async with fetch in another function在另一个函数中使用 fetch 训练 promise 和 await / async
【发布时间】:2020-10-11 06:06:45
【问题描述】:

我继续练习 JS。

这一次,我尝试使用 async / await 或 promise 做同样的事情:

const url = 'https://jsonplaceholder.typicode.com/todos/1';
  1. 异步/等待版本:
async function getData() {
    const response = await fetch(url);
    const data = await response.json();
    return data;
}

const callGetData = async () => {
    try {
        const data = await getData()
        console.log(data);        
    } catch (error) {
        console.log("Something gone wrong")        
    }
}
  1. 承诺版
function getData() {
    return new Promise((resolve, reject) => {
        fetch(url)
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(error => reject(error));
    });
}

const callGetData = () => {
    getData()
    .then(data => console.log(data))
    .catch(error => console.log("Something gone wrong"));
}

最后:

callGetData();

两个 sn-ps 似乎都可以工作。写 async / await 版本对我来说更容易。

问题:

  • 在这种情况下我可以正确使用 Promise 吗?
  • 是否有一些可能的改进?

感谢您的帮助。

【问题讨论】:

    标签: node.js promise async-await fetch


    【解决方案1】:

    fectch 也是一个promise,您正试图将一个promise 包装在一个新的Promise

    更多关于 Promise 版本,您可以简单地从函数中返回它

    getData(url){
     return fetch(url)
     .then(response => response.json()).then(jsonResponse=>jsonResponse)
     .catch(err=>err)
    }
    

    现在getData 返回一个承诺。我们可以简单地这样做:

    getData().then(data=>console.log(data))
    

    【讨论】:

    • 非常感谢您的回答。这一点很明显。我知道我错了。
    猜你喜欢
    • 2020-09-22
    • 2021-05-13
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 2019-09-25
    • 2018-01-14
    • 1970-01-01
    相关资源
    最近更新 更多