0

How come I get result from setTemplate before I get result from getTemplateHtml ?

Shouldn't it wait for getTemplateHtml to resolve before it moves to the next one?

From my Angular Controller:

mail.chooseTemplate = async function() {
    var res = "";
    res = await mail.getTemplateHtml();
    res = await mail.setTemplate(res);
};    

mail.getTemplateHtml = () => {
    return new Promise((resolve, reject) => {        
    $http({
        method:  'GET',
        url:     "templates/mail" + mail.emailRecord.template + ".html",
        headers: { 'Content-Type': 'text/html' }

    }).then((response) => {
        console.log("getTemplateHtml!!")
        resolve(response.data);
        return;
    })
    .catch((error) => {
        reject();
        return;
    })
})};

mail.setTemplate = (templateData) => {
    return new Promise((resolve, reject) => {        
    console.log("setTemplate!!")
    mail.showMail = replaceField(templateData);
    resolve();
})};
torbenrudgaard
  • 2,375
  • 7
  • 32
  • 53
  • 1
    Where do you use `mail.chooseTemplate` function? – felixmosh Sep 08 '17 at 10:05
  • *How come I get result from setTemplate before I get result from getTemplateHtml* - how did you test that? *promises are not waiting for resolve* - they are. This is how they work. Please, provide http://stackoverflow.com/help/mcve . The code above uses promise constructor antipattern, but this shouldn't be a problem. If the problem is that `showMail` isn't updated in view, this is because you're using native promises and `async` which aren't compatible with Angular digests. – Estus Flask Sep 08 '17 at 10:23
  • Possible duplicate of [Typescript async/await doesnt update AngularJS view](https://stackoverflow.com/questions/39943937/typescript-async-await-doesnt-update-angularjs-view) – Estus Flask Sep 08 '17 at 10:23
  • @estus ahhh so its digest that is messing it up here? Its easy to test, the res from getTemplateHtml never reaches setTemplate. The value `templateData` is always undefined. And even with debug and stepping thru, it does not wait for resolve before continuing. – torbenrudgaard Sep 08 '17 at 10:40
  • 1
    There will be problems with digests, but you're possibly still not there. Something in your debugging process went wrong (don't trust a debugger if you rely only on what it shows). The scenario you're describing is impossible in the code above. If `response.data` is ok, it will be passed. http://stackoverflow.com/help/mcve is necessary here, otherwise the question can be considered off-topic. Please, provide a way to recreate the problem - a plunk, etc. – Estus Flask Sep 08 '17 at 11:06
  • 1
    You should avoid the [explicit promise construction antipattern](https://stackoverflow.com/questions/23803743/what-is-the-explicit-promise-construction-antipattern-and-how-do-i-avoid-it) `$http` returns a promise, use it, don't abuse it :p (this has nothing to do with your problem though) – Jaromanda X Sep 08 '17 at 11:52

0 Answers0