Pat*_*841 5 javascript node.js promise chain bluebird
我使用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');
});
Run Code Online (Sandbox Code Playgroud)
我正在使用最新的蓝鸟通过:
npm install --save bluebird
我接近这个错吗?我将不胜感激任何帮助.谢谢.
它抛出该错误是因为,没有方法testSecond
,testFirst
如果你想在两个 Promise 都解决后做某事,请像下面这样做:
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`
});
Run Code Online (Sandbox Code Playgroud)
如果您想检查两者是否都已正确解析,请不要执行 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';
});
}
Run Code Online (Sandbox Code Playgroud)
console.log
现在,在回调中执行如下所示的操作spread
,将记录上面的承诺返回的字符串:
Promise.join(sample.testFirst(), sample.testSecond()).spread(function(first, second){
console.log(first); // test_first
console.log(second); // test_second
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
325 次 |
最近记录: |