【问题标题】:insert async function inside then然后在里面插入异步函数
【发布时间】:2021-04-28 12:29:45
【问题描述】:

如果Promise 成功,我想使用axios get 方法发出一个获取请求并链接一个发布请求

端点是一个 API,Promise 应该从 Get Request 返回 Promise,返回 GET Request Promise

考虑到这个答案calling a async function inside then 这应该是可能的

为什么post请求没有通过?

axios.get('https://reqres.in/api/users/')
.then(() => {
    data = {
        email: 'eve.holt@reqres.in',
        password: 'pistol'
    }
    return data
}).then((data) => {
    const postRequest = axios.post('https://reqres.in/api/register', data);
    return postRequest
}).then((response) => {
    console.log(response)
}).catch((response) => {
    console.log(response)
});
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Http Requests & JavaScript</title>
        <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"> 
        </script>
    </head>

    <body>
    </body>
</html> 

【问题讨论】:

    标签: javascript promise axios


    【解决方案1】:

    如果你使用异步,那么使用await 怎么样?我现在已经使用await 翻译了您的代码。

    // test.js
    const axios = require('axios');
    
    const test = async () => {
        try {
            await axios.get('https://reqres.in/api/users/');
            const data = {
                email: 'eve.holt@reqres.in',
                password: 'pistol'
            }
            const registerResult = await axios.post('https://reqres.in/api/register', data);
            console.log(registerResult);
        } catch (error) {
            console.log(error);
        }
    };
    
    test();
    
    • 等待axios.get()函数正常执行后,axios.post()会被执行。
    • 如果从axios.get() 进程返回错误,则错误为thrown,并将立即停止。然后,错误会记录在catch() 函数中。
    • (当然)另外,即使axios.get()函数正常工作,如果axios.post()函数出现问题,也会catch()出错。

    [P.S] 另外如果你想通过axios.get()得到结果,你可以在将结果赋值给像const users = await axios.get()这样的变量后使用它

    【讨论】:

    • async/await.then().then() Promise 风格相比看起来非常干净,或者更糟糕的是,一个很好的旧回调地狱。赞成,这就是要走的路
    • 我刚刚意识到我的代码也可以工作,但您的解决方案看起来更干净!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-09-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多