2017-01-02 37 views
0

我需要做两个http请求。第二个http请求需要来自第一个请求的信息。第一个请求是设置第二个请求期间使用的变量'amount'。我如何使用承诺一个单一的变量?

这是我的codesection。

(变量“网址”和“数量”是存在的,foo()从别的东西。)

var Promise = require('bluebird'); 
var request = require('request-promise'); 
var amount; 


request({url: url, json: true }, function(error, response, body) { 
      if (!error && response.statusCode == 200) { 
      amount = body.num; 
      } 
     }).then(function(data) { 
      if (number == null || number > amount) { 
      number = Math.floor(Math.random() * amount) + 1; 
      } 

      request({ 
      url: url, 
      json: true 
      }, function(error, response, body) { 
      if(!error & response.statusCode == 200) { 
       foo(); 
      } 
      }); 
     }); 

代码工作,但它是不美与此筑巢的请求。有没有办法让一个变量的承诺,然后触发一个函数,当该变量已设置?

+0

您正在使用['request-promise'](https://github.com/request/request-promise),但仍然使用非承诺回调。为什么? –

+0

'number'从哪里来? –

回答

2

您正在使用request-promise但仍使用旧式回调,这就是为什么事情看起来如此混乱。

很难分辨出你想要做什么,但如果第二个请求依赖于信息从第一,你把它放在一个then回调并返回新的承诺,它给你:

var Promise = require('bluebird'); 
// I changed `request` to `rp` because `request-promise` is not `request`, that's one of its underlying libs 
var rp = require('request-promise'); 

// Do the first request 
rp({ url: url, json: true }) 
    .then(function(data) { 
     // First request is done, use its data 
     var amount = data.num; 
     // You didn't show where `number` comes from, assuming you have it in scope somewhere... 
     if (number == null || number > amount) { 
      number = Math.floor(Math.random() * amount) + 1; 
     } 
     // Do the next request; you said it uses data from the first, but didn't show that 
     return rp({ url: url, json: true }); 
    }) 
    .then(function() { // Or just `.then(foo);`, depending on your needs and what `foo` does 
     // Second request is done, use its data or whatever 
     foo(); 
    }) 
    .catch(function(error) { 
     // An error occurred in one of the requests 
    }); 
+0

非常感谢!它帮助我:) – ivsterr

相关问题