在 promise 中循环直到另一个 promise 结束
While loop in promise until another promise ends
我需要使用 REDIS(异步工作)测试是否设置了值,然后再让我的代码变为 运行。
我开始使用此处定义的 Loop Promise:
我已经试过了,但不幸的是我被一个未决的承诺所困:
promise: { state: 'pending' }
function promiseWhile(condition, body) {
var done = Q.defer();
function loop() {
/** When the result of calling condition is no longer true, we are done */
if(!condition())
return done.resolve();
/** Use 'when', in case `body` does not return a promise */
/** When it completes loop again otherwise, if it fails, reject the done promise */
Q.when(body(), loop, done.reject);
}
/** Start running the loop in the next tick so that this function is completely async */
/** It would be unexpected if body was called synchronously the first time */
Q.nextTick(loop);
return done.promise;
}
var timeline_id = 3;
promiseWhile(function () {
return Q.ninvoke(redisClient, 'hget', 'hashTest', timeline_id).then(function (result) {
console.log(result + '<---->');
return result;
});
}, function () {
return Q.delay(500);
}).then(function () {
// Let's continue process...
});
我需要检查间隔,因为如果 timeline_id 已经在处理中,我需要等待,直到 timeline_id 在 Redis 上从 hashTest 中删除。
我如何确定我得到了结果而不是承诺状态来检查我是否仍然可以 运行 我的循环。
终于,我找到了实现这个的方法...
当然不是很优雅,但我现在不能做得更好:
var redisState = true;
promiseWhile(function () {
/** Loop until true */
return redisState;
}, function (result) {
return Q.ninvoke(redisClient, 'HGET', 'hashTest', timeline_id).then(function(result) {
redisState = result;
if (redisState) {
redisState = result;
return Q.delay(500);
}
});
}).then(function() {
...
}):
我需要使用 REDIS(异步工作)测试是否设置了值,然后再让我的代码变为 运行。
我开始使用此处定义的 Loop Promise:
我已经试过了,但不幸的是我被一个未决的承诺所困:
promise: { state: 'pending' }
function promiseWhile(condition, body) {
var done = Q.defer();
function loop() {
/** When the result of calling condition is no longer true, we are done */
if(!condition())
return done.resolve();
/** Use 'when', in case `body` does not return a promise */
/** When it completes loop again otherwise, if it fails, reject the done promise */
Q.when(body(), loop, done.reject);
}
/** Start running the loop in the next tick so that this function is completely async */
/** It would be unexpected if body was called synchronously the first time */
Q.nextTick(loop);
return done.promise;
}
var timeline_id = 3;
promiseWhile(function () {
return Q.ninvoke(redisClient, 'hget', 'hashTest', timeline_id).then(function (result) {
console.log(result + '<---->');
return result;
});
}, function () {
return Q.delay(500);
}).then(function () {
// Let's continue process...
});
我需要检查间隔,因为如果 timeline_id 已经在处理中,我需要等待,直到 timeline_id 在 Redis 上从 hashTest 中删除。
我如何确定我得到了结果而不是承诺状态来检查我是否仍然可以 运行 我的循环。
终于,我找到了实现这个的方法...
当然不是很优雅,但我现在不能做得更好:
var redisState = true;
promiseWhile(function () {
/** Loop until true */
return redisState;
}, function (result) {
return Q.ninvoke(redisClient, 'HGET', 'hashTest', timeline_id).then(function(result) {
redisState = result;
if (redisState) {
redisState = result;
return Q.delay(500);
}
});
}).then(function() {
...
}):