[英]Typescript: how to call a Javascript function with a callback
I am using Ionic with Typescript. 我正在使用Ionic和Typescript。 I need to access the following api :
我需要访问以下api :
load(key, successCallback/*(value)*/, failCallback)
In Typescript I do the following: 在Typescript中,我执行以下操作:
cordova.plugins.icloudkv.load('key').then((data) => {
console.log(data);
alert('load key: ' + JSON.stringify(data));
});
}
}).catch((e) => {
console.error(JSON.stringify(e));
this.doAlert('iCloud: ' + JSON.stringify(e));
});
However, the alert
is never getting fired. 但是,
alert
永远不会被解雇。
Question 题
Please can someone advise what's the best way to invoke the javascript function using typescript? 有人可以建议使用typescript调用javascript函数的最佳方法是什么?
Thanks 谢谢
According to the api you've provided your code should look more like: 根据api你提供的代码看起来应该更像:
cordova.plugins.icloudkv.load('key',
(data)=>{
console.log(data);
alert('load key: ' + JSON.stringify(data));
}, (e)=>{
console.error(JSON.stringify(e));
this.doAlert('iCloud: ' + JSON.stringify(e));
});
Are you getting any errors in the console? 你在控制台中收到任何错误吗?
Your code assumes that load
returns a Promise. 您的代码假定
load
返回Promise。 See if this works, since the example explicitly asks for two callbacks in the load
method: 看看这是否有效,因为该示例明确要求在
load
方法中有两个回调:
cordova.plugins.icloudkv.load('key', (data) => {
console.log(data);
alert('load key: ' + JSON.stringify(data));
}, (e) => {
console.error(JSON.stringify(e));
this.doAlert('iCloud: ' + JSON.stringify(e));
});
If you prefer to work with a Promise
even though the api doesn't use one then construct a Promise
around the call: 如果你喜欢使用
Promise
即使api没有使用它,那么围绕调用构建一个Promise
:
new Promise((resolve, reject) => cordova.plugins.icloudkv.load('key', resolve, reject))
.then((data) => {
console.log(data);
alert('load key: ' + JSON.stringify(data));
});
}
}).catch((e) => {
console.error(JSON.stringify(e));
this.doAlert('iCloud: ' + JSON.stringify(e));
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.