您能告诉我为什么以下测试没有通过吗?
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用作promise中的异步函数 - 这应该只是单独工作 - 。
谢谢
答案 0 :(得分:2)
你需要调用函数来返回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
})
})