JavaScript(node.js)-异步等待不起作用

时间:2018-08-27 18:16:06

标签: javascript node.js asynchronous promise async-await

我在使用异步/等待时遇到一些问题。如果我致电getAccountDetails,我只会收到undefined,然后我会收到日志

  

getOpengraphResponse没问题

但是我使用async / await。请求是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;
              }

      });
    }
}

2 个答案:

答案 0 :(得分:1)

您只能(有用)i一个承诺。

await不返回承诺。它根本没有return语句,因此它返回getOpengraphResponse

您需要将undefined的返回值视为一个承诺。不要将其传递给回调函数。请使用request.getthen

返回所需的值(如果您在awaitawait)或返回值getOpengraphResponse

答案 1 :(得分:1)

async / await可以用promises实现。即

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。