Reputation: 53
I have some problems using async/await. If i call getAccountDetails
i only get undefined
and afterwards i get the log
getOpengraphResponse
is ok
But i use async/await. And request is request-promise-native
. At position one should be the log
getOpengraphResponse
is ok
and then the property details
should be displayed. Where is my mistake?
const https = require('https');
const request = require('request-promise-native');
let openGraphBaseURL = "https://graph.facebook.com//v3.1/";
class Account{
constructor(name){
this.name = name;
}
}
class InstagramAccount extends Account{
async getAccountDetails(EdgeID, token){
this.EdgeID = EdgeID;
this.token = "&access_token=" + token;
this.command = this.EdgeID+"?fields=name,username,website,biography,followers_count,follows_count,media_count,profile_picture_url"+this.token;
this.details = await this.getOpengraphResponse(this.command);
console.log(this.details);
}
getOpengraphResponse(command){
request.get({
url: openGraphBaseURL+command,
json: true,
headers: {'User-Agent': 'request'}
}, (err, res, data) => {
if (err) {
console.log('Error: ', err);
}else if (res.statusCode !== 200) {
console.log('Status:', res.statusCode);
} else {
console.log('getOpengraphResponse is ok');
return data;
}
});
}
}
Upvotes: 0
Views: 4420
Reputation: 1341
async/await can implemented with promises. i.e
var function_name = function(){
// Create a instance of promise and return it.
return new Promise(function(resolve,reject){
// this part enclose some long processing tasks
//if reject() or resolve()
//else reject() or resolve()
});
}
//function which contains await must started with async
async function(){
// you need to enclose the await in try/catch if you have reject statement
try{
await function_name(); // resolve() is handled here.
console.log('this will execute only after resolve statement execution');
}catch(err){
// reject() is handled here.
console.log('this will execute only after reject statement execution');
}
}
You can also use then/catch instead of try/catch.
Upvotes: 3
Reputation: 943097
You can only (usefully) await
a promise.
getOpengraphResponse
doesn't return a promise. It has no return statement at all, so it returns undefined
.
You'll need to treat the return value of request.get
as a promise. Don't pass it a callback. Do use then
or await
.
Return either the value you want (if you await
inside getOpengraphResponse
) or the return value of request.get
.
Upvotes: 1