如何在JavaScript中使用Promise [英] How to use promises in javascript
问题描述
我正在使用Typescript在Cordova中为Android开发一个应用程序,并且将其与Webpack捆绑在一起.我不太了解如何在Javascript中执行异步任务.我看到了一些有关回调和Promise的教程,但是对我来说仍然很困惑,我无法设法使其适应我的代码.我不知道我的问题是来自代码本身,还是来自Typescript/Cordova/Webpack.
I am making an app for Android in Cordova, with Typescript, and I bundle with Webpack. I don't understand very well how to do asynchronous tasks in Javascript. I saw several tutorials on callbacks and promises, but it's still very confused for me and I don't manage to adapt it to my code. I don't know if my problem comes from my code itself, or from Typescript/Cordova/Webpack.
我创建了一个函数 getAllSMS
,该函数返回一个大对象,并且需要一些时间来执行.我知道该功能有效,因为如果我尝试在检查器的控制台中打印 allSMS
变量,则该变量首先为空,然后在1秒钟内填充.(我认为检查员的行为很奇怪,但确实如此).
I created a function getAllSMS
that return a big object, and takes some time to execute. I know the function works because if I try to print the allSMS
variable in the inspector's console, it's empty at first and then filled in like 1 second. (I think that behavior of the inspector is quite strange, but it really does that).
我看到我可以用promises来执行异步任务,但是我在理解它的工作方式时遇到了一些问题.我看过几本教程,但我仍然不明白如何将其应用到我的代码中.
I saw I can do asynchronous tasks with promises, but I have some problems to understand how it works. I have seen several tutorials but I still don't understand how to apply it to my code.
谢谢
:这是将我的getAllSMS函数转换为Promise:
: Here's my getAllSMS function converted to a promise :
public getAllSMS() {
return new Promise(//return a promise
(resolve,reject)=>{
if (SMS) {
SMS.listSMS(this.filters, function (data) {
resolve(data);//added this, resolve promise
}, function (err) {
console.log('error list sms: ' + err);
reject(err);//added this reject promise
});
}else{
resolve([]);//added this, resolving to empty array?
}
}
).then(
data=>{
let contacts = {};
for (let key in data) {
if ((data[key].address).length > 7 && (data[key].address).match("[0-9]+")) {
let date = SMSManager.convertUnixDate(data[key].date); // on converti le format de date de listSMS
if (contacts.hasOwnProperty(data[key].address)) {
Object.defineProperty(contacts[data[key].address], data[key]._id, {
value: {
"body": data[key].body,
"date": date
}
});
} else {
let myid = String(data[key]._id);
Object.defineProperty(contacts, data[key].address, {
value: {
"000": {
"body": data[key].body,
"date": date
}
}
});
}
}
}
return contacts;
}
);
}
我这样调用我的函数,但是我的for in循环仍未执行,尽管我的变量似乎已正确加载.
EDIT 2 : I call my function like that, but my for in loop is still not executed , although my variable seems correctly loaded.
sms.getAllSMS().then( allSMS => {
console.log('allSMS');
console.log(allSMS);
console.log('then is readed'); // this is readed
for (let key in allSMS) {
console.log(allSMS[key]); // this is not executed
}
}).catch(
error => console.warn("something is wrong")
);
这是控制台的屏幕截图(控制台中的对象"为allSMS).在对象"旁边有一个小"i"字样:下面的值现在才被求值".
Here's a screenshot of the console ('Object' in the console is allSMS). Next to "Object" there's a little "i" that says : "Value below was just evaluated right now".
推荐答案
我怀疑sms.getAllSMS返回了Promise,因此您可以尝试以下操作:
I suspect sms.getAllSMS returns a promise so you can try the following:
sms.getAllSMS()
.then(
allSMS => {
for (let key in allSMS) {
console.log(allSMS[key]);
}
}
)
.catch(
error=>console.warn("something went wrong, error is:",error)
)
您的getAllSMS不返回任何内容,请确保它返回了一个Promise:
Your getAllSMS does not return anything, make sure it returns a promise:
public getAllSMS(): object {
return new Promise(//return a promise
(resolve,reject)=>{
if (SMS) {
SMS.listSMS(this.filters, function (data) {
resolve(data);//added this, resolve promise
}, function (err) {
console.log('error list sms: ' + err);
reject(err);//added this reject promise
});
}else{
resolve([]);//added this, resolving to empty array?
}
}
).then(
data=>{
let contacts = {};
data.forEach(
item=>{
if ((item.address).length > 7 && (item.address).match("[0-9]+")) {
let date = SMSManager.convertUnixDate(item.date); // on converti le format de date de listSMS
if (contacts.hasOwnProperty(item.address)) {
Object.defineProperty(contacts[item.address], item._id, {
value: {
"body": item.body,
"date": date
}
});
} else {
Object.defineProperty(contacts, item.address, {
value: {
"000": {
"body": item.body,
"date": date
}
}
});
}
};
}
);
return contacts;
}
);
}
这篇关于如何在JavaScript中使用Promise的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!