从承诺链内部解决问题安全吗?
Safe to resolve from inside a promise chain?
恐怕我做的是完全错误的。
是否可以使用承诺链 IN 承诺来 resolve() 或 reject()。
// Insert a new user by details into database
insert: function(username, name, email, gender, birthday, other) {
return new Promise(function(resolve, reject) {
// Base structure
var new_user = {
username: username,
name: name,
email: email,
gender: gender,
birthday: birthday
};
// Merge other data with base structure
if(other != undefined) {
new_user = _.merge(new_user, other);
}
var new_user_model = new UserModel(new_user);
new_user_model.saveAsync(function(user) {
return resolve(user); // Safe to resolve from inside a promise?
});
// OR... should I do it like this?
var user = new_user_model.saveAsync(function(user) {
return user;
});
return resolve(user);
});
}
实际上您不需要在此处 resolve
或 reject
。您可以 return new_user_model.saveAsync
给您的承诺:无需将其包装在新的承诺中。请尝试以下操作。
// Insert a new user by details into database
insert: function(username, name, email, gender, birthday, other) {
// Base structure
var new_user = {
username: username,
name: name,
email: email,
gender: gender,
birthday: birthday
};
// Merge other data with base structure
if(other != undefined) {
new_user = _.merge(new_user, other);
}
var new_user_model = new UserModel(new_user);
return new_user_model.saveAsync();
}
恐怕我做的是完全错误的。
是否可以使用承诺链 IN 承诺来 resolve() 或 reject()。
// Insert a new user by details into database
insert: function(username, name, email, gender, birthday, other) {
return new Promise(function(resolve, reject) {
// Base structure
var new_user = {
username: username,
name: name,
email: email,
gender: gender,
birthday: birthday
};
// Merge other data with base structure
if(other != undefined) {
new_user = _.merge(new_user, other);
}
var new_user_model = new UserModel(new_user);
new_user_model.saveAsync(function(user) {
return resolve(user); // Safe to resolve from inside a promise?
});
// OR... should I do it like this?
var user = new_user_model.saveAsync(function(user) {
return user;
});
return resolve(user);
});
}
实际上您不需要在此处 resolve
或 reject
。您可以 return new_user_model.saveAsync
给您的承诺:无需将其包装在新的承诺中。请尝试以下操作。
// Insert a new user by details into database
insert: function(username, name, email, gender, birthday, other) {
// Base structure
var new_user = {
username: username,
name: name,
email: email,
gender: gender,
birthday: birthday
};
// Merge other data with base structure
if(other != undefined) {
new_user = _.merge(new_user, other);
}
var new_user_model = new UserModel(new_user);
return new_user_model.saveAsync();
}