首页 > 解决方案 > 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;
              }

      });
    }
}

标签: javascriptnode.jsasynchronouspromiseasync-await

解决方案


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。


推荐阅读