[英]Promise resolve not working
我无法确定我的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消息,但是我希望它会在诺言返回后出现。
显然,我在这里犯了一个新手错误,但我看不到它是什么。
错误是if(this.success)
因为您将异步代码视为同步代码。 您创建的新承诺内的所有内容都将同步运行。
查看输出,应该很直接地了解发生了什么:
if
将评估为true
并解析尚未定义的值。 put()
函数调用完成,并将响应记录到控制台。 您还将实现延迟的反模式 。 由于put()
函数已经返回了一个,因此无需创建新的Promise。 只需返回那个,然后从.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;
});
}
您不必创建新的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);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.