繁体   English   中英

异步/等待在 NodeJS 中不起作用,它不等待

[英]async/await not working in NodeJS, it doesn't wait

我在 NodeJS 中使用 Axios 调用 2 REST API 端点。我试图让代码逐行执行,但第二个( viewProfile() )function 不等待generateId();

const generateId = async (data) => {
    const options = optionsBuilder("post","profile", data);
    try {
        const response = await axios(options);
        id = response.data.id;
        console.log(id);
    } catch (error) {
        console.error(error);
    }
}
const viewProfile = async (profileId) => {
    console.log('Test 2', profileId);
    const path = `blog/${profileId}`;
    const options = optionsBuilder("get", path);
    try {
        const response = await axios(options);
        console.log(response.data);  
    } catch (error) {
        console.log(error);
        }
    }
}
...
generateId(data);
viewProfile(profileId);

您必须将它们执行到异步 scope 中:

(async function(){
    await generateId(data);
    await viewProfile(profileId);
})()    

否则它们不会被解析为等待并且viewProfile将在generateId之后立即执行。 :)

因为,如果您使用的是新的 ES2022,您可以await进入顶层。

对于较新的 Node.js 版本:

await generateId(data);
await viewProfile(profileId);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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