承诺不按顺序返回值
promise not returning value in order
你好,我是 ionic 的新手,
我想在后台从 pouch-db
获取数据。
在做了一些研究后我发现,promise 的概念将解决我的问题。
我想按照以下 1、2 和 3 给出的顺序执行我的控制台日志
这是我的代码:
Class:
class1{
method1(){
class2Provider.method2().then(function (result:any) {
console.log("3")
console.log("VSCP "+result);
this.navCtrl.push('InspectionPage',{'inspectnData':result});
})
}
}
提供商 1:
export class ModelProvider {
method2(){
return new Promise (resolve => {
this.dbHelpr.getRecord().then(function (result:any) {
console.log("2")
console.log("data for inspectId is -------------"+JSON.stringify(tempData));
resolve(result)
})
})
}
}
提供商 2:
export class DbHelperProvider {
getRecord(){
return new Promise(resolve => {
this.db.get(_id).then(function (doc) {
console.log("1")
resolve(doc);
}).catch(function (err) {
console.log(err);
resolve("fail");
});
})
}
}
以上代码首先执行日志 3 并显示
错误
Cannot read property 'navCtrl' of undefined
如何按我想要的顺序执行函数?
使用胖箭头函数 =>
而不是 function
。
class1{
method1(){
class2Provider.method2().then((result: any) => {
console.log("3")
console.log("VSCP " + result);
this.navCtrl.push('InspectionPage', { 'inspectnData': result });
})
}
}
你好,我是 ionic 的新手,
我想在后台从 pouch-db
获取数据。
在做了一些研究后我发现,promise 的概念将解决我的问题。
我想按照以下 1、2 和 3 给出的顺序执行我的控制台日志
这是我的代码:
Class:
class1{
method1(){
class2Provider.method2().then(function (result:any) {
console.log("3")
console.log("VSCP "+result);
this.navCtrl.push('InspectionPage',{'inspectnData':result});
})
}
}
提供商 1:
export class ModelProvider {
method2(){
return new Promise (resolve => {
this.dbHelpr.getRecord().then(function (result:any) {
console.log("2")
console.log("data for inspectId is -------------"+JSON.stringify(tempData));
resolve(result)
})
})
}
}
提供商 2:
export class DbHelperProvider {
getRecord(){
return new Promise(resolve => {
this.db.get(_id).then(function (doc) {
console.log("1")
resolve(doc);
}).catch(function (err) {
console.log(err);
resolve("fail");
});
})
}
}
以上代码首先执行日志 3 并显示
错误Cannot read property 'navCtrl' of undefined
如何按我想要的顺序执行函数?
使用胖箭头函数 =>
而不是 function
。
class1{
method1(){
class2Provider.method2().then((result: any) => {
console.log("3")
console.log("VSCP " + result);
this.navCtrl.push('InspectionPage', { 'inspectnData': result });
})
}
}