我有一个需要发送的消息列表,其间有1秒的延迟。 目前我正在使用此功能:
send() {
return new Promise((resolve, reject) => {
this._send(resolve);
});
}
_send(resolve, index) {
index = index || 0;
if (this.messages.length && index < this.messages.length) {
if (this.messages[index]) {
let response = this.messages[index];
response.send().then(() => {
this._schedule(resolve, index);
});
} else
this._schedule(resolve, index);
}
else
resolve();
}
_schedule(resolve, index) {
setTimeout(() => {
this._send(resolve, ++index);
}, 1000);
}
这是好方法吗?我注意到当这个部分运行时,节点使用的ram比平时多。
我正在使用Bluebird for Promise。
更新基于@ Roamer的评论:
基于文档:
Promise.reduce( Iterable<any>|Promise<Iterable<any>> input, function(any accumulator, any item, int index, int length) reducer, [any initialValue] ) -> Promise
_wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
__send() {
return Promise.reduce(this.messages, function (dummy, response, index, len) {
return response.send().then(() => {
return this._wait(1000);
}).catch(() => {
//don't care about a error , continue to the next one
return this._wait(1000);
});
}).then(() => {
return true;
});
}
这是对的吗?