为什么没有承诺的testing通过?

前几天我进入了一个美好的诺言世界,我只是觉得我已经开悟了。 承诺看起来很简单,但他们可以混淆。

你能告诉我为什么下面的testing不通过?

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接收,我猜?

实际上,通过这个testing,我想了解如何使用相互依赖的promise,以及如何在promise中使用promises作为asynchronous函数 – 这些工作应该单独工作。

谢谢

你需要调用函数来返回promise,比如

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

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

例如。

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

最后,为了使你的testing工作,你也需要修改

  .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