javascript - 如何对单个变量使用 Promise?

标签 javascript node.js request promise bluebird

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

这是我的代码段。

(变量“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();
            }
          });  
        });

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

最佳答案

您正在使用request-promise,但仍然使用老式的回调,这就是为什么事情看起来如此困惑。

很难弄清楚您要做什么,但如果第二个请求依赖于第一个请求的信息,您可以将其放入 then 回调中并返回它为您提供的新 promise :

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

关于javascript - 如何对单个变量使用 Promise?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41432349/

相关文章:

javascript - 如何阻止跨域脚本?

javascript - vue-test-utils 在按钮上点击触发器不触发

javascript - 如何在 PhoneGap 的 windows 平台上实现 map (Google 或 Bing)?

javascript - request.js 中的永久代理 - 如何检查它是否正常工作

node.js - 告诉服务器用户不再上网

ios - cordova Framework7 中的 Ajax 错误函数

javascript - 如何在 iframe 中的不同 URL 之间移动?

javascript - Chrome 中的慢 cors 预检选项请求

android - ionic 1、 ionic 和 ionic 3 之间有什么区别? ionic 2 和 ionic3 是一样的吗?

Python - 如何知道您已使用 urllib2 登录