【问题标题】:how do I use promise for a single variable?如何将 promise 用于单个变量?
【发布时间】:2017-05-16 21:16:28
【问题描述】:

我需要做两个 http 请求。第二个 http 请求需要来自第一个的信息。第一个请求是设置在第二个请求期间使用的变量“金额”。

这是我的一段代码。

(变量 'url' 和 'number' 存在,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();
            }
          });  
        });

代码可以运行,但是这种嵌套的请求并不美观。有没有办法对变量做出承诺,然后在设置该变量时触发函数?

【问题讨论】:

  • 您正在使用request-promise,但仍在使用非承诺回调。为什么?
  • number 来自哪里?

标签: javascript node.js request promise bluebird


【解决方案1】:

您正在使用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
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-08
    • 2020-08-22
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    相关资源
    最近更新 更多