- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想测试数组的每个元素,直到满足条件,然后跳过其余的。这是我想出的代码,它似乎有效,但我不确定它是否真的安全或有意想不到的副作用。欢迎其他解决方案。
let buddyAdded = false;
replicaArr = _.keys(ReplicaList);
Promise.each(replicaArr, function(replicaname) {
if (!buddyAdded) {
Player.count({
'buddyList': replicaname
}, function(err, result) {
if (err) {
} else if (result < 990) {
Player.update({
'_id': buddyObj.buddyId
}, {
'buddyList': replicaname
}, function(err) {
if (err) {
} else {
ReplicaList[replicaname].send(buddyObj);
buddyAdded = true;
// success stop here and skip all the other array elements
return;
}
});
}
});
}
});
最佳答案
如果您尝试一次连续枚举一个玩家,并在发现好友列表中有空间的玩家时中止迭代,您可以更新列表并传达发生的任何错误,那么这里有一种方法这样做。
其工作原理如下:
Promise.promisifyAll()
自动为 Player
对象创建 Promise 返回方法,以便我们可以在控制流中使用这些方法。Promise.mapSeries()
一次连续迭代一个数组。Player.countAsync()
和 Player.updateAsync()
方法,以便它们正确排序并从 .mapSeries()
返回它们因此它会等待它们完成,然后再继续迭代到下一个数组元素。.mapSeries()
停止其迭代(这就是您所说的您想要的)。.catch()
来测试特殊拒绝并将其转换为成功解决的 promise 。如果是其他错误,则让它继续作为实际错误传播。代码:
// Promisify the Player object so the methods
// this would usually be done wherever this module is loaded
Player = Promise.promisifyAll(Player);
// create a special subclass of Error for our short circuit
PlayerUpdateDone extends Error {
constructor(name) {
super();
this.name = name;
}
}
// put logic into a function to make it cleaner to use
function addToBuddyList(replicaArr) {
return Promise.mapSeries(replicaArr, function(replicaname) {
return Player.countAsync({buddyList: replicaname}).then(function(result) {
// if room left in buddy list
if (result < 990) {
return Player.updateAsync({'_id': buddyObj.buddyId}, {'buddyList': replicaname}).then(function() {
ReplicaList[replicaname].send(buddyObj);
// throw special exception to abort .mapSeries()
// and stop further processing
throw new PlayerUpdateDone(replicaname);
});
}
});
}).then(function() {
// if it gets here, there were no players with rooms so just return null
return null;
}).catch(function(result) {
// we used a special rejection as a shortcut to stop the mapSeries from executing
// the rest of the series
if (result instanceof PlayerUpdateDone) {
// change this special rejection into a result
return result.name;
}
// must have been regular error so let that propagate
throw result;
});
}
// sample usage
addToBuddyList(replicaArr).then(function(name) {
if (name) {
console.log(`Updated player ${name}`);
} else {
console.log("No players with room in their buddy list");
}
}).catch(function(err) {
// error here
console.log(err);
});
<小时/>
制作自己的定序器可能会更简单,当第一个 promise 解析为真值时停止:
// fn will be passed each array element in sequence
// fn should return a promise that when resolved with a truthy value will stop the iteration
// and that value will be the resolved value of the promise that is returned from this function
// Any rejection will stop the iteration with a rejection
Promise.firstToPassInSequence = function(arr, fn) {
let index = 0;
function next() {
if (index < arr.length) {
return Promise.resolve().then(function() {
// if fn() throws, this will turn into a rejection
// if fn does not return a promise, it is wrapped into a promise
return Promise.resolve(fn(arr[index++])).then(function(val) {
return val ? val : next();
});
});
}
// make sure we always return a promise, even if array is empty
return Promise.resolve(null);
}
return next();
};
Promise.firstToPassInSequence(replicaArr, function(replicaname) {
return Player.countAsync({buddyList: replicaname}).then(function(result) {
// if room left in buddy list
if (result < 990) {
return Player.updateAsync({'_id': buddyObj.buddyId}, {'buddyList': replicaname}).then(function() {
ReplicaList[replicaname].send(buddyObj);
return replicaname;
});
}
});
});
关于javascript - Bluebird.each 如果解决则中断,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41784895/
bluebird.js和bluebird.core.js有什么区别? 什么时候应该使用bluebird.core.js而不是bluebird.js? 我无法在bluebird site或其他地方找到任
我正在从异步转换为 Bluebird,但不知道如何打破循环 这是我想要实现的目标: 循环数据数组。 对于每个项目,检查它是否存在于数据库中。 将一个项添加到数据库(第一个不存在的项),然后退出.eac
我试图用 .try(function(){}).catch(function(){}) 块返回一个 promise 。我的问题是由我的 promise 类型引起的。 deleteProcess
我正在尝试使用 bluebird 的 .return() 来扩展 promise 解析值方法。 目前我正在使用以下代码: doSomethingAsync() // assu
我刚刚开始使用 Promise 和 Bluebird。调试时我可以看到我的函数执行了两次: 首先我收到此错误:TypeError:未捕获错误:无法读取未定义的属性“then” 然后我看到函数再次执行,
我想测试数组的每个元素,直到满足条件,然后跳过其余的。这是我想出的代码,它似乎有效,但我不确定它是否真的安全或有意想不到的副作用。欢迎其他解决方案。 let buddyAdded = false; r
假设我有以下 node.js 代码 function foo() { return promiseOne().then(function(result) { return pr
假设我想在从数据库查找用户后同时发送电子邮件并向客户端推送通知,我可以这样写 User.findById(userId).exec() .then(() => sendMail()) .then(()
.call 方法的 Bluebird 文档有 code sample标记为“链接破折号或下划线方法”。 下面的代码片段中链接的 .then(_) 的用途是什么? var Promise = requi
是否有某种方法可以检索从上一个 then 回调返回的任何内容(或传递给初始 Promise.resolve()/resolve())? const p = Bluebird.resolve().the
我有以下代码。当 f2 没有抛出错误时,它工作正常。 如果有错误,它会生成一个Unhandled rejection Error。 重写代码以避免 Unhandled rejection Error
我有一个来自这篇文章的后续问题:Chaining Requests using BlueBird/ Request-Promise 我对 promise 很陌生,所以请原谅我的天真。我成功地实现了这段
我是 Bluebird 的新手,我正在尝试创建一个新用户,但 reject 函数没有按预期工作。 问题是它为我创建了用户,即使它启动了错误There nickname is already in us
我正在尝试实现剪刀石头布游戏的 CLI 版本。我正在使用查询器模块来处理 IO。我的主要功能如下所示: RockPaperScissors.prototype.gameLoop = function(
此代码运行正常: let promise; try { promise = parent(); //but I want: await parent(); await cont
在 promise 了 fs-extra 后,我知道我可以使用 then 来访问文件。我猜想有某种机制,在获取文件后,它知道要移动到 then 链中的下一个链接。然而,接下来的then我只是放置了一个
我有以下代码。它按预期工作,没有抛出未处理的拒绝错误。 p = new Promise (fulfill, reject) -> reject new Error 'some error' p.c
我期待 Bluebird forgotten return warning出现,但由于某种原因它不起作用。 A demo : const Bluebird = require('bluebird');
我正在使用 bluebird图书馆结束memcached . memcached.set('foo', 'bar', 10, function (err) { /* stuff */ }); 此函数不
我正在尝试如下使用 Bluebird 的协程: var p = require('bluebird'); //this should return a promise resolved to valu
我是一名优秀的程序员,十分优秀!