为什么这个带有承诺的测试没有通过?

Why doesn't this test with promises pass?

几天前,我走进了美好的承诺世界,我只是觉得我开悟了。 Promise 看起来很简单,但它们可能会令人困惑。

你能告诉我为什么下面的测试没有通过吗?

var Promise = require('bluebird');
var expect = require('chai').expect;
var request = Promise.promisifyAll(require('request'));

describe('Promise', function() {
    it('should work again', function() {

        var final_result;

        function first_promise() {
            return new Promise(function(resolve, reject) {
                resolve("http://www.google.com");
            })
        }

        function second_promise() {
            return new Promise(function(resolve, reject) {
                resolve("This is second promise!");
            })
        }

        function inner_async_request(url_from_first_promise) {
            return new Promise(function(resolve, reject) {
                return request.getAsync(url_from_first_promise).spread(function(response, content) {
                    final_result = content;
                    resolve(content);
                })
            })
        }

        return request.getAsync('http://127.0.0.1:3000/').spread(function(result, content) {
                //do something with content and then return first_promise
                console.log(content);
                return first_promise;
            })
            .then(function(url) {
                inner_async_request(url).then(function(result) {
                    console.log(result);
                    final_result = result;
                })
                return second_promise;
            })
            .then(function(result) {
                // result should be "This is second promise!"
                console.log(result);
                // final_result should be google's html
                expect(final_result).not.to.be.undefined;
            })
    });
});

目前的错误是:Unhandled rejection Error: options.uri is a required argument 我猜应该从 first_promise 收到?

实际上,通过这个测试,我想了解如何使用相互依赖的 promises 以及如何将 promises 用作 promises 中的异步函数——它们应该单独工作——。

谢谢

你需要调用函数来return promises,比如

 return request.getAsync('http://localhost:3000/').spread(function(result, content) {
         //do something with content and then return first_promise
         console.log(content);
         return first_promise();
     })

在某些情况下,您根本不需要创建新的承诺

例如

function inner_async_request(url_from_first_promise) {
    return request.getAsync(url_from_first_promise).spread(function(response, content) {
        final_result = content;
        return content;
    })
}

最后,为了让你的测试工作,你还需要修改它

    .then(function(url) {
        // return 
        return inner_async_request(url).then(function(result) {
            console.log(result);
            final_result = result;
            return second_promise(); // return second promise inside then
        })
    })

DEMO