Unable to access response object data outside the function in node js

六月ゝ 毕业季﹏ 提交于 2019-12-25 19:01:46

问题


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:

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:


回答1:


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));


来源:https://stackoverflow.com/questions/52258510/unable-to-access-response-object-data-outside-the-function-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!