Skip to content Skip to sidebar Skip to footer

How To Use Promises In Javascript

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 tutori

Solution 1:

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)
)

Your getAllSMS does not return anything, make sure it returns a promise:

public getAllSMS(): object {
  returnnewPromise(//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 listSMSif (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;
    }
  );
}

Solution 2:

You fixed the asynchrony problem now by using promises, that looks fine.

The problem with the for loop not enumerating your properties is that Object.defineProperty does (by default) create non-enumerable properties. Use a simple assignment instead:

let contacts = {};
for (const key indata) {
    const address = data[key].address;
    if (address.length > 7 && address.match("[0-9]+")) {
        const date = SMSManager.convertUnixDate(data[key].date); // on converti le format de date de listSMSconst myid = String(data[key]._id);
        if (address in contacts) {
            contacts[address][myid] = {
                "body": data[key].body,
                "date": date
            };
        } else {
            contacts[address] = {
               "000": {
                   "body": data[key].body,
                   "date": date
                }
            }
        }
    }
}
return contacts;

Post a Comment for "How To Use Promises In Javascript"