javascript - JavaScript(node.js) - 异步等待不起作用
问题描述
我在使用 async/await 时遇到了一些问题。如果我打电话,getAccountDetails
我只会得到undefined
,然后我会得到日志
getOpengraphResponse
没问题
但我使用异步/等待。请求是request-promise-native
. 第一个位置应该是日志
getOpengraphResponse
没问题
然后details
应该显示该属性。我的错误在哪里?
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;
}
});
}
}
解决方案
async/await 可以用 Promise 来实现。IE
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');
}
}
您也可以使用 then/catch 代替 try/catch。
推荐阅读
- swift - NSWindow“已编辑”未显示
- c++ - std::initializer_list 堆是否分配内存?
- c - 将字符串中的一个单词替换为另一个单词
- python - 将多个列表添加到现有数据框的最佳方法
- firebase - 说所有 NoSQL 提供程序都对读/写操作收费是否正确?
- google-cloud-platform - 通过 HTTP 请求打开/关闭 GCP Compute Engine 实例
- apache-spark - 以自动/智能方式在执行之间将数据帧缓存到磁盘
- python-3.x - 在 Keras Sequential 模型中使用 LayerNormalization 的可能解决方法
- git - 如何修复预提交挂钩失败的错误消息
- reactjs - 嵌套路由不渲染