Unable to access response object data outside the

2019-09-20 07:10发布

I am using node js and making a call to spotify API and receive the response in body object, as shown in below code:

    var options = {
          url: 'https://api.spotify.com/v1/me',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
    };
    request.get(options, function(error, res, body) {
          console.log(body)
    });

This gives me output: enter image description here

But now when I try to access the body object outside the function I get undefined. I think the problem is that I am making an asynchronous call and so before the response is received the statements where I make use of body variable outside function are executed. But I am a bit confused about how to get to the solution.

Any help is appreciated

Edit:

    request.get(options, function(error, res, body) {
        console.log(body)
        response.render('user_account.html', {
                data: body
        })
    });

And it gives the output:

enter image description here

1条回答
男人必须洒脱
2楼-- · 2019-09-20 08:16

Use promise.

You can try following:

const apiCall = () => {
  return new Promise((resolve, reject) => {
    var options = {
          url: 'https://api.spotify.com/v1/me',
          headers: { 'Authorization': 'Bearer ' + access_token },
          json: true
    };
    request.get(options, function(error, res, body) {
          if(error) reject(error);
          console.log(body);
          resolve(body);
    });
  });
}

apiCall().then((body) => {
    // do your things here
})
.catch((err) => console.log(err));
查看更多
登录 后发表回答