【问题标题】:Promise resolve not working承诺解决不起作用
【发布时间】:2017-01-10 02:46:22
【问题描述】:

我无法弄清楚我的 Angular 2 代码做错了什么。我的承诺没有返回正确的结果。

我的代码如下所示:

  this.addPlan('My plan title9', "YES9")
  .then((id)=>{
      console.log('Promise return was: ' + id);
    })
  .catch((err)=>{
      console.log('Call to addPlan failed with err = ' + err);
    });

  addPlan(title, security)
  {
    let timeStamp 	= new Date().toISOString();
    let plan 		= {
        _id 		  : 'PLAN:' + timeStamp,
        title 		: title,
        security 	: security,
        notes     : [],         
        flags     : [],         
        created   : timeStamp,
        updated 	: timeStamp
      };

    return new Promise(resolve =>
    {
      var theID;
      this._DB.put(plan)
      .then(function (response) {
        console.log(JSON.stringify(response));
        resolve(response.id);
        theID = response.id;
      })
      .catch((err) =>
      {
        console.log('addPlan error is: ' + err);
        this.success = false;
      });

      if(this.success)
      {
        this.handleSyncing();
        resolve(theID);
      }

    });
  }

this.addPlan(...) 被调用时,服务器日志是:

Promise return was: undefined 
{"ok":true,"id":"PLAN:2017-01-09T18:16:50.094Z","rev":"1-ac45a4785982fcbbcb46dd099431ecb6"}

当它应该是'id'的值时,承诺的回报是未定义的。控制台也首先显示 Promise 消息,但我希望它会在 Promise 返回后出现。

显然我在这里犯了一个新手错误,但我看不到它是什么。

【问题讨论】:

    标签: javascript angular promise


    【解决方案1】:

    错误是if(this.success),因为您将异步代码视为同步代码。您创建的新 Promise 块内的所有内容都将同步运行。

    查看输出,应该很容易理解发生了什么:

    1. if 将评估为 true 并解决尚未定义的问题 价值。
    2. put() 函数调用完成并将响应记录到控制台。

    您也在实施deferred anti-pattern。无需创建新的 Promise,因为 put() 函数已经返回了一个。只需返回那个并从.then() 中返回响应,它将把它包装在一个promise 中并解决它。我在下面的代码中省略了this.handleSyncing();,因为它的作用并不完全清楚。

    function addPlan(title, security) {
      let timeStamp = new Date().toISOString();
      let plan = {
        _id: 'PLAN:' + timeStamp,
        title: title,
        security: security,
        notes: [],         
        flags: [],         
        created: timeStamp,
        updated: timeStamp
      };
    
      return this._DB.put(plan)
        .then((response) => {
          console.log(JSON.stringify(response));
          return response.id;
        //^^^^^^----- This will wrap the response.id in a promise and will be the resolved value 
        })
        .catch((err) => {
          console.log('addPlan error is: ' + err);
          this.success = false;
        });  
    }
    

    【讨论】:

      【解决方案2】:

      你不必创建一个新的 Promise

      你可以只返回 "this._DB.put(plan)" 承诺:

      addPlan(title, security){
          let timeStamp   = new Date().toISOString();
          let plan        = {
              _id           : 'PLAN:' + timeStamp,
              title       : title,
              security    : security,
              notes     : [],         
              flags     : [],         
              created   : timeStamp,
              updated     : timeStamp
            };
          return this._DB.put(plan).then(response => {
              return response.id
          })
        }
      

      then() 上的响应将等于 id:

       this.addPlan('My plan title9', "YES9").then((id)=>{
            console.log('Promise return was: ' + id);
          })
      

      【讨论】:

        猜你喜欢
        • 2017-08-03
        • 2020-04-15
        • 1970-01-01
        • 2015-11-17
        • 2015-06-24
        • 2017-04-29
        • 2018-03-19
        • 2016-05-06
        相关资源
        最近更新 更多