我将一些数据保存到Polymer元素中的Firebase数据库中。一切正常。但是,作为Promises的新手,我需要帮助来理解方法末尾的Promise.resolved()
意味着什么。在使用.then
之前,还没有承诺通过吗?那到底是做什么的呢?我看了around,但无法找到resolved()
没有价值的示例。
如何将其更改为具有更为熟悉的结构,如下所示:
.then(function(snapshot) {
// The Promise was "fulfilled" (it succeeded).
}, function(error) {
// The Promise was rejected.
});
这是块Promise.resolved()
取自documentation:
saveData : function() {
this.$.document.data = this.$.message.value;
this.$.document.save("/parent", "child").then(function() {
console.log('sent the event!!!!!!');
this.$.document.reset();
}.bind(this));
return Promise.resolve();
},
答案 0 :(得分:4)
首先,您需要了解Promise的基础知识。
让我们从非常基础开始 -
新创建的es6承诺处于以下状态之一:
让我们创建一个示例Promise
var promise = new Promise(function(fulfill, reject) {
// Do some stuff and either fullfill or reject the promise
});
因此,上述承诺会收到一个回调函数,该函数也称为 executor 函数,其签名为function(fullfill, reject)
。
新创建的promise还有一个非常重要的属性函数then
,用于链接和控制逻辑流程。
then
有两个可选的回调参数onFulfilled
和onRejected
。
在这个执行者函数中,有两件事情表明了承诺的结果 -
fullfill
方法:
表示操作已成功完成。如果您使用值调用履行,则onFulfilled
中的then
回调将获得该值,如果您决定不在{{{{}}中提供值1}}然后使用参数fulfill
调用onFulfilled
。
undefined
var promise = new Promise(function(fulfill, reject) {
// lets assume operation completed successfully
fulfill('Success');
});
promise.then(onFulfilled, onRejected);
function onFulfilled(result) {
console.log(result);
// Success will be printed
}
方法在有或没有值的情况下被调用:
执行操作时发生了一些问题。您可以决定是否传递一些错误消息reject
回调以指示最终用户发生错误。
reject
现在让我们谈谈var promise = new Promise(function(fulfill, reject) {
// lets assume operation did not complete successfully
reject(new Error('Error'));
});
promise.then(onFulfilled, onRejected);
function onRejected(error) {
console.log(error.message);
// Error message will be printed
}
。
在顶部,您学习了如何通过构造函数创建promise。
Promise.resolve
同样来自var promise = new Promise(function (fulfill, reject) {
fulfill('Success value');
});
// Now: Promise.resolve
// Exactly does the same thing as above code
var promise = Promise.resolve('Success value');
-
Promise.reject
在您的情况下,var promise = new Promise(function (fulfill, reject) {
reject(new Error('Error VALUE'));
});
var promise = Promise.reject(new Error('Error VALUE'));
似乎已经在内部返回承诺,承诺可能会调用save
或fulfill
方法,因此您无需致电{{1} }。您只需要在reject
方法中获取该承诺返回的值Promise.resolve()
值或fulfilled
值。
rejected
我希望它能使承诺更加清晰。
答案 1 :(得分:1)
如果您正在努力做obj.saveData().then(...)
,那么您可以像这样返回内部承诺:
saveData : function() {
this.$.document.data = this.$.message.value;
// return this promise
return this.$.document.save("/parent", "child").then(function() {
console.log('sent the event!!!!!!');
this.$.document.reset();
}.bind(this));
}