[英]Bluebird Promise Bind Chain
我使用Bluebird进行承诺并尝试允许链调用但是使用.bind()似乎不起作用。 我正进入(状态:
TypeError:sample.testFirst(...)。testSecond不是函数
第一个方法被正确调用并启动了promise链但是我还没有能够让实例绑定工作。
这是我的测试代码:
var Promise = require('bluebird');
SampleObject = function()
{
this._ready = this.ready();
};
SampleObject.prototype.ready = function()
{
return new Promise(function(resolve)
{
resolve();
}).bind(this);
}
SampleObject.prototype.testFirst = function()
{
return this._ready.then(function()
{
console.log('test_first');
});
}
SampleObject.prototype.testSecond = function()
{
return this._ready.then(function()
{
console.log('test_second');
});
}
var sample = new SampleObject();
sample.testFirst().testSecond().then(function()
{
console.log('done');
});
我正在使用最新的蓝鸟通过:
npm install --save bluebird
我接近这个错吗? 我将不胜感激任何帮助。 谢谢。
它抛出了这个错误,因为在testSecond
上没有方法testSecond
,如果你想在两个testFirst
被解析后做某事,就像下面这样做:
var sample = new SampleObject();
Promise.join(sample.testFirst(), sample.testSecond()).spread(function (testFirst, testSecond){
// Here testFirst is returned by resolving the promise created by `sample.testFirst` and
// testSecond is returned by resolving the promise created by `sample.testSecond`
});
如果要检查两者是否都已正确解析,而不是执行console.log,请在testFirst
和testSecond
函数中返回该字符串,并将其记录在spread
回调中,如下所示:
SampleObject.prototype.testFirst = function()
{
return this._ready.then(function()
{
return 'test_first';
});
}
SampleObject.prototype.testSecond = function()
{
return this._ready.then(function()
{
return 'test_second';
});
}
现在,在spread
回调中执行console.log
,如下所示,将记录上面的promises返回的字符串:
Promise.join(sample.testFirst(), sample.testSecond()).spread(function(first, second){
console.log(first); // test_first
console.log(second); // test_second
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.