简体   繁体   English

NodeJS请求从函数返回JSON

[英]NodeJS Request return JSON from function

I've read a couple of posts about this here (callbacks) but I still don't really fully understand how to solve my problem. 我在这里已经读过几篇有关此问题的文章(回调),但是我仍然不太了解如何解决我的问题。 So I was hoping that somebody here could help me with mine and I would get it better. 所以我希望这里有人可以帮助我,我会做得更好。

Simple put I want the ID I get from the first request to be used for the second request. 简单地说,我希望从第一个请求获得的ID用于第二个请求。

I'm new to JavaScript and NodeJS in general. 我是JavaScript和NodeJS的新手。

 function idRequest(name) { var options = { ... }; function callback(error, response, body) { if (response.statusCode == 200 && !error) { const info = JSON.parse(body); //console.log(info.accountId); return info.accountId; } } request(options, callback); } function requestById(accountId) { var options = { ... }; function callback(error, response, body) { if (response.statusCode == 200 && !error) { const info = JSON.parse(body); console.log(info); } } request(options, callback); } var id = idRequest('..'); requestById(id); 

Try by returning a promise from the first function and inside it resolve the callback, so the once it is resolved , you can use it's then to trigger the second function 尝试从第一个函数返回一个promise,并在其内部解决回调,因此一旦解决,便可以使用它来触发第二个函数

function idRequest(name) {
  var options = {
    ...
  };

  function callback(error, response, body) {
    if (response.statusCode == 200 && !error) {
      const info = JSON.parse(body);
      //console.log(info.accountId);
      return info.accountId;
    }
  }
  return new Promise(function(resolve, reject) {
    resolve(request(options, callback))

  })
}

function requestById(accountId) {

  var options = {
    ...
  };

  function callback(error, response, body) {
    if (response.statusCode == 200 && !error) {
      const info = JSON.parse(body);
      console.log(info);
    }
  }

  request(options, callback);
}

var id = idRequest('..').then(function(data) {
  requestById(data);
});

since callback is a async call, so var id will be undefined , when you call the requestById(id); 因为回调是异步调用,所以当您调用requestById(id);时, var id将是undefined requestById(id);

so either you can use the promise method, answered by @brk or you can call your requestById(id) function directly from the first callback. 因此,您可以使用由@brk回答的promise方法,也可以直接从第一个回调直接调用requestById(id)函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM