JavaScript (node.js) - асинхронное ожидание не работает - PullRequest
0 голосов
/ 27 августа 2018

У меня проблемы с использованием 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 голосов
/ 27 августа 2018

async / await может быть реализовано с обещаниями. * 1001 то есть *

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.

0 голосов
/ 27 августа 2018

Вы можете только (с пользой) await обещание.

getOpengraphResponse не возвращает обещание. У него вообще нет оператора возврата, поэтому он возвращает undefined.

Вам нужно будет обработать возвращаемое значение request.get как обещание. Не передавайте это обратный вызов. Используйте then или await.

Возвращает либо нужное вам значение (если вы await внутри getOpengraphResponse), либо возвращаемое значение request.get.

...