2017-01-02 36 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

相關問題