简体   繁体   中英

sync function call in Node

I think I have a little leak in understand the async sync workflow in node. I hope someone can tell me what is my leak or what I do wrong.

I have a basic function

app.get('/', function(req, res) {

    console.log("step 1");

    myOAuthLogic();

    console.log("step 2");
});

For myOAuthLogic I use a async function that call a promise:

function oauthPage(url) {

    return new Promise((resolve, reject) => {
        axios.request({
            url: "/oauth2/token?grant_type=client_credentials",
            method: "POST",
            baseURL: "https://xxx/",
            auth: {
                username: "xxx",
                password: "xxx"
            },
            headers: { 'content-type': 'application/x-www-form-urlencoded' },
            data: {
                "grant_type": "client_credentials",
                "scope": "user" 
            }
        }).then(res => {
            resolve(res.data.access_token);
        }).catch(error => {
            console.log(error.response.status);
            resolve("");
        });
    });

}

async function myOAuthLogic() {
    try {
        const token = await oauthPage('https://xxx/')
        console.log(token);
    } catch (error) {
        console.error('ERROR:');
        console.error(error);
    }
}

What I expect is:

  1. step 1
  2. token
  3. step 2

But what I get is

  1. step 1
  2. step 2
  3. token

I thought that the async with await will cause the function to wait until ready. What I understand wrong here?

use async/await for router function also.

app.get('/', async function(req, res) {
    try{
        console.log("step 1");
        await myOAuthLogic();
        console.log("step 2");
    }catch(err){
        console.log(err);
        res.sendStatus(500);
    }
});

Note: no need to create new promise you can directly return axios.request .

function oauthPage(url) {
    return axios.request({
        url: "/oauth2/token?grant_type=client_credentials",
        method: "POST",
        baseURL: "https://xxx/",
        auth: {
            username: "xxx",
            password: "xxx"
        },
        headers: { 'content-type': 'application/x-www-form-urlencoded' },
        data: {
            "grant_type": "client_credentials",
            "scope": "user" 
        }
    });
}

You need to add async and await to treat your promise function:

app.get('/', async function(req, res) {

console.log("step 1");

await myOAuthLogic();

console.log("step 2");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM