需要帮助了解此承诺并处理错误

时间:2016-11-13 04:43:21

标签: firebase promise polymer firebase-realtime-database polymerfire

我将一些数据保存到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();
        },

2 个答案:

答案 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有两个可选的回调参数onFulfilledonRejected

在这个执行者函数中,有两件事情表明了承诺的结果 -

    使用或不使用值调用
  • 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')); 似乎已经在内部返回承诺,承诺可能会调用savefulfill方法,因此您无需致电{{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));
 }