axios の応答を返したいのですが、返される応答は常に未定義です。
wallet.registerUser=function(data){
axios.post('http://localhost:8080/register',{
phone:data.phone,
password:data.password,
email:data.email
}).then(response =>{
return response.data.message;
console.log(response.data.message);
}).catch(err =>{
console.log(err);
})
}
console.log(wallet.registerUser(data));
コンソールは常に undefined としてログに記録されます。この応答を返す方法はありますか。
ベストアンサー1
console.log は、関数が完全に完了するまでログに記録しません。つまり、非同期にする必要があります。wallet.registerUser
これを行うには、主に 2 つの方法があります。
コールバック - これは、axios 呼び出しが終了すると実行される既存の関数に関数をパラメータとして渡す場合です。コードでの動作は次のようになります。
wallet.registerUser=function(data, callback){ axios.post('http://localhost:8080/register',{ phone:data.phone, password:data.password, email:data.email }).then(response =>{ callback(response.data.message); console.log(response.data.message); }).catch(err =>{ console.log(err); }) } wallet.registerUser(data, function(response) { console.log(response) });
Promise - これを行う最も簡単な方法は、
async
関数名の前に を置くことです。これにより、関数から返されるものはすべて Promise の形式で返されます。コード内での動作は次のようになります。wallet.registerUser=async function(data){ axios.post('http://localhost:8080/register',{ phone:data.phone, password:data.password, email:data.email }).then(response =>{ return response.data.message; console.log(response.data.message); }).catch(err =>{ console.log(err); }) } wallet.registerUser(data).then(function(response) { console.log(response); });
非同期関数に関する詳細情報は次のとおりです。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function