[英]sync function call in Node
我認為我在理解節點中的異步同步工作流方面有些漏水。 我希望有人能告訴我我的泄漏是什么或我做錯了什么。
我有一個基本功能
app.get('/', function(req, res) {
console.log("step 1");
myOAuthLogic();
console.log("step 2");
});
對於myOAuthLogic,我使用一個異步函數來調用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);
}
}
我期望的是:
但是我得到的是
我以為與await的異步將導致函數等待直到准備就緒。 我在這里理解錯了嗎?
也將async / await用於路由器功能。
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);
}
});
注意:無需創建新的axios.request
您可以直接返回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"
}
});
}
您需要添加異步並等待以處理您的Promise函數:
app.get('/', async function(req, res) {
console.log("step 1");
await myOAuthLogic();
console.log("step 2");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.