Javascript 承诺不起作用
我搞不清楚我的Angular 2代码到底做错了什么。我的承诺不会返回正确的结果 我的代码如下所示:Javascript 承诺不起作用,javascript,angular,promise,Javascript,Angular,Promise,我搞不清楚我的Angular 2代码到底做错了什么。我的承诺不会返回正确的结果 我的代码如下所示: this.addPlan(“我的计划标题9”,“是9”) 。然后((id)=>{ log('承诺返回为:'+id); }) .catch((错误)=>{ log('调用addPlan失败,错误='+错误); }); addPlan(标题、安全性) { 让timeStamp=new Date().toISOString(); 让计划={ _id:“计划:”+时间戳, 标题:标题,, 安全:安全,
this.addPlan(“我的计划标题9”,“是9”)
。然后((id)=>{
log('承诺返回为:'+id);
})
.catch((错误)=>{
log('调用addPlan失败,错误='+错误);
});
addPlan(标题、安全性)
{
让timeStamp=new Date().toISOString();
让计划={
_id:“计划:”+时间戳,
标题:标题,,
安全:安全,
注:[],
旗帜:[],
创建:时间戳,
更新:时间戳
};
返回新承诺(解决=>
{
var theID;
这是我的计划
.然后(功能(响应){
log(JSON.stringify(response));
解析(response.id);
theID=response.id;
})
.catch((错误)=>
{
log('addPlan错误为:'+err);
成功=错误;
});
如果(这是成功)
{
这个。handleSyncing();
决心(theID);
}
});
}错误是if(this.success)
,因为您将异步代码视为同步代码。您创建的新承诺块中的所有内容都将同步运行
从输出来看,应该相当直截了当地理解发生了什么:
if
将计算为true
,并解决尚未定义的问题
价值观
put()
函数调用完成并将响应记录到控制台
您还正在实现。无需创建新的承诺,因为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;
});
}
你不必做出新的承诺
您只需返回“this.\u DB.put(plan)”承诺:
然后()上的响应将等于id:
this.addPlan('My plan title9', "YES9").then((id)=>{
console.log('Promise return was: ' + id);
})
this.addPlan('My plan title9', "YES9").then((id)=>{
console.log('Promise return was: ' + id);
})