【问题标题】:difference between different scenarios of async awaitasync await 不同场景的区别
【发布时间】:2020-05-24 17:41:00
【问题描述】:

以下场景有什么区别:

场景 1 - axios 请求中的异步等待 - 不起作用

export const getAll = async () => {
    const retrievedData = await axios.get('http://localhost:3001/anecdotes'); // should return - Array
    return retrievedData.data;
};


const test = () => {
        let anecdotes = getAll();
        // do something 
    };

场景 2 - 辅助方法中的异步等待不起作用

export const getAll = () => {
    const retrievedData = axios.get('http://localhost:3001/anecdotes'); // should return - Array
    return retrievedData.data;
};


const test = async () => {
        let anecdotes = await getAll();
        // do something 
    };

场景 3 - 两个 WORKS 中的异步等待

export const getAll = async() => {
    const retrievedData = await axios.get('http://localhost:3001/anecdotes'); // should return - Array
    return retrievedData.data;
};


const test = async () => {
        let anecdotes = await getAll();
        // do something 
    };

以上场景有什么区别? 为什么只有第三种情况有效?

【问题讨论】:

    标签: javascript reactjs promise async-await


    【解决方案1】:

    为什么只有第三种情况有效??

    所有async 函数都返回一个promise - 总是。当您 return async 函数中的值时,该值将成为 async 函数返回的承诺的解析值。

    此外,axios() 返回一个 promise,因此您还需要在其返回值上使用 .then() 或 await 以从 axios() 调用中获取结果。

    场景 1

    在场景 1 中,您的 getAll() 函数是 async 并返回一个承诺。那么您的 test() 函数不会在该承诺上使用 await 或 .then():

    const test = () => {
            let anecdotes = getAll();
            // do something 
    };
    

    因此anecdotes 只是一个承诺,您实际上并没有从承诺中获得价值。您需要在该承诺上使用 await 或 .then() 才能获得价值。


    场景 2

    场景 2 的问题略有不同。在getAll()你这样做:

    export const getAll = () => {
        const retrievedData = axios.get('http://localhost:3001/anecdotes');
        return retrievedData.data;
    }
    

    axios.get() 返回一个承诺。所以,retrievedData 是一个承诺。这不是你想要的结果。当您 return retrievedData.data 时,您只是返回了一个不存在的 Promise 属性,因此它将始终返回 undefined。


    场景 3

    在场景 3 中,您确实在 async 函数的结果和 axios() 调用的结果上成功使用了 await,因此它可以工作。

    export const getAll = async() => {
        const retrievedData = await axios.get('http://localhost:3001/anecdotes'); // should return - Array
        return retrievedData.data;
    };
    
    
    const test = async () => {
        let anecdotes = await getAll();
        // do something 
    };
    

    【讨论】:

    • await axios.get('http://localhost:3001/anecdotes'); 为什么在解决或拒绝承诺之前,以下行不暂停执行?
    • @lynxx - 它暂停函数的内部执行,但在它启动 axios() 函数的那一刻,await 告诉 JS 立即从该函数和外部世界返回一个承诺继续。然后,当axios() 承诺解决时,该函数再次恢复,然后当它最终执行return 时,设置已经返回的承诺的已解决值。这里要理解的重要一点是await 只暂停函数的内部执行,而不是其余的代码流。
    • @lynxx - 在第一个 await 处,函数返回一个承诺,随后的调用者继续执行。这就是为什么调用者必须在 async 函数的结果上使用 await 或 .then() 的原因,因为 promise 在值已知之前返回的函数。只有当该承诺解决时,才会知道该值。所以,await 只在函数内部暂停。 await 不会停止代码流中的所有内容。它只会停止执行它所在的 async 函数,并且在此时,它会立即返回一个 Promise。
    猜你喜欢
    • 2023-04-10
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 2015-01-14
    • 1970-01-01
    • 2019-10-08
    • 2020-09-16
    • 2021-11-05
    相关资源
    最近更新 更多