2017-01-09 139 views
0

我不能解决我做错了我的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 \t = new Date().toISOString(); 
 
    let plan \t \t = { 
 
     _id \t \t : 'PLAN:' + timeStamp, 
 
     title \t \t : title, 
 
     security \t : security, 
 
     notes  : [],   
 
     flags  : [],   
 
     created : timeStamp, 
 
     updated \t : 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消息,但我希望它在承诺返回后出现。

显然,我在这里做一个新手的错误,但我看不出它是什么。

回答

2

错误是if(this.success)因为你处理异步代码就好像它是同步的。您创建的新承诺块内的所有内容都将同步运行。

望着输出,它应该是相当简单的理解发生了什么:

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

您还在执行deferred anti-pattern。因为put()函数已经返回一个函数,所以不需要创建新的承诺。只需返回那一个,并返回.then()内的响应,它会将其包装在承诺中并予以解决。我在下面的代码中省略了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; 
    }); 
} 
1

您不必创建一个新的承诺

你可以返回 “this._DB.put(计划)” 的承诺:

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 
    }) 
    } 

和响应,然后()将相等于ID:

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