我一直在为我自己使用的小型2D游戏库工作,我遇到了一些问题.库中有一个名为loadGame的特定函数,它将依赖信息作为输入(资源文件和要执行的脚本列表).这是一个例子.
loadGame({
"root" : "/source/folder/for/game/",
"resources" : {
"soundEffect" : "audio/sound.mp3",
"someImage" : "images/something.png",
"someJSON" : "json/map.json"
},
"scripts" : [
"js/helperScript.js",
"js/mainScript.js"
]
})
Run Code Online (Sandbox Code Playgroud)
资源中的每个项目都有一个密钥,游戏使用该密钥来访问该特定资源.loadGame函数将资源转换为promises对象.
问题是它试图使用Promises.all来检查它们何时准备就绪,但是Promise.all只接受迭代作为输入 - 所以像我所拥有的对象是不可能的.
所以我尝试将对象转换为数组,这很有效,除了每个资源只是数组中的一个元素,并且没有用于标识它们的键.
这是loadGame的代码:
var loadGame = function (game) {
return new Promise(function (fulfill, reject) {
// the root folder for the game
var root = game.root || '';
// these are the types of files that can be loaded
// getImage, getAudio, and getJSON are defined elsewhere in my code - they …Run Code Online (Sandbox Code Playgroud) 我在OSX上使用最新的节点版本7.1.0,但我仍然无法使用Promises.我明白了
index.js
new Promise();
Run Code Online (Sandbox Code Playgroud)
错误:
Run Code Online (Sandbox Code Playgroud)new Promise(); ^TypeError:Promise resolver undefined不是函数
节点7.1.0不支持ES6和Promise吗?
我在myCreate中定义了我的钩子如下:
module.exports = function (sequelize, DataTypes) {
var userSchema = sequelize.define('User', {
// define...
});
userSchema.beforeCreate(function (model) {
debug('Info: ' + 'Storing the password');
model.generateHash(model.password, function (err, encrypted) {
debug('Info: ' + 'getting ' + encrypted);
model.password = encrypted;
debug('Info: ' + 'password now is: ' + model.password);
// done;
});
});
};
Run Code Online (Sandbox Code Playgroud)
当我创建一个模型
User.create({
name: req.body.name.trim(),
email: req.body.email.toLowerCase(),
password: req.body.password,
verifyToken: verifyToken,
verified: verified
}).then(function (user) {
debug('Info: ' + 'after, the password is ' + user.password);
}).catch(function (err) …Run Code Online (Sandbox Code Playgroud) 这是使用deffered/promise实现某些异步函数超时的常见模式:
// Create a Deferred and return its Promise
function timeout(funct, args, time) {
var dfd = new jQuery.Deferred();
// execute asynchronous code
funct.apply(null, args);
// When the asynchronous code is completed, resolve the Deferred:
dfd.resolve('success');
setTimeout(function() {
dfd.reject('sorry');
}, time);
return dfd.promise();
}
Run Code Online (Sandbox Code Playgroud)
现在我们可以执行一些调用的异步函数myFunc并处理超时:
// Attach a done and fail handler for the asyncEvent
$.when( timeout(myFunc, [some_args], 1000) ).then(
function(status) {
alert( status + ', things are going well' );
},
function(status) {
alert( status + ', …Run Code Online (Sandbox Code Playgroud) 我知道推迟分离承诺状态控制和处理,这里使用Q作为例子,承诺返回的承诺Q.defer().promise和Q.Promise完全不同,为什么设计这样?这两个"承诺"有什么区别
提前致谢
PS:我目前正在开发Promise库,欢迎使用issws和PRS:https://github.com/XiaomingJS/Xiaoming.Promise
我在循环中进行多个mongoDB查询.并且想要将所有结果作为一个数据数组发送.但是当我简单地使用return来发送数据时,它只返回undefined而不等待所有数据库请求的结果.我也尝试过使用q.moulde但同样的问题.
码:
var getPrayerInCat = function(data){
var result ;
var finalData = [];
if(data.length >0){
data.forEach(function(data2){
var id= data2.id;
Prayer.find({prayerCat:id},function(err,prayer){
var deferred = Q.defer()
if (err) { // ...
console.log('An error has occurred');
// res.send(err);
result= finalData = err
} else {
if(!prayer){
// console.log(data2.id+'--0');
data2.prayersCount = 0;
result = deferred.resolve(finalData.push(data2))
} else {
// console.log(data2.id+'--'+prayer.length);
data2.prayersCount = prayer.length;
// console.log(prayer)
result = deferred.resolve(finalData.push(data2))
} // else for data forward
}
deferred.promise;
})
// deferred.resolve(finalData);
})
/*if(finalData.length > 0) { …Run Code Online (Sandbox Code Playgroud) 我开始async/await在我的js应用程序中使用ES7函数(由Babel编译).
纠正我,如果错了,但他们只与Promises合作吗?如果是,这意味着我需要将常规回调函数包装到Promises中(我目前正在做什么).
使用mongoose来查询db和Q for promises的结果,但是发现很难找到一个可用的用户列表.目前我有这样的事情:
var checkForPerson = function( person ) {
people = mongoose.model('Person', Person)
return people.findOne({"_id": person }, function(err, doc) {
if (err) console.log(err)
if (doc !== null) {
return doc
} else {
console.log('no results')
}
})
}
var promises = someArrayOfIds.map(checkForPerson);
// this is where I would like to have an array of models
var users = Q.all(promises)
//this fires off before the people.findOne query above to users is undefined
SomeOtherFunction( users )
Run Code Online (Sandbox Code Playgroud)
如果SomeOtherFunction没有做大量的草率回调,我将如何完成查询?
在https://pragprog.com/book/tbajs/async-javascript这本书中,我发现了这个:
Node的早期迭代在其非阻塞API中使用了Promises.然而,在2010年2月,Ryan Dahl做出了切换到现在熟悉的回调(错误,结果......)格式的决定,理由是Promises是属于"userland"的更高级别的构造.
它看起来很混乱,因为作为读取文件的API,这个
fs.readFile('/etc/passwd')
.onSuccess(function(data){console.log(data)})
.onError(function(err){throw err})
Run Code Online (Sandbox Code Playgroud)
看起来比这更好:
fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
有没有人知道为什么"Promise是一个更高级别的构造"会阻止自己在NodeJS API中使用?
既然ES6是Node 4.x的官方标准,你如何使用Promises?模块(例如本机fs模块)是否自动与Promises一起使用?或者必须专门编写模块以与Promises一起使用?你怎么知道什么可以使用Promise而你不能使用什么?
已经有很多不同的Promise实现(Q,Bluebird等),我很困惑从Node 4.x中的本机Promise开始.
promise ×8
javascript ×7
node.js ×6
asynchronous ×2
mongodb ×2
q ×2
async-await ×1
babeljs ×1
deferred ×1
ecmascript-6 ×1
jquery ×1
mongoose ×1
nonblocking ×1
sequelize.js ×1