编程语言
首页 > 编程语言> > Javascript-承诺解决后如何呈现模板?

Javascript-承诺解决后如何呈现模板?

作者:互联网

解决承诺后,我想返回要在父级中呈现的模板.我知道不能从诺言中返回价值.收到模板数据后,如何渲染模板?

在以下示例中,ContentPane是父级,列出了要渲染的所有模板.在电影中,进行网络呼叫,因此需要呈现模板.

ContentPane.prototype.getTemplate = function(){
    let template = `
        <div class="contentPane" id="contentPane">
        ${new Films().render()}
        </div>
    `;
    return template;
}


Films.prototype.render =  function(){
    var template =  this.getTemplate();
    template.then(function(val){
        return val;
    })
    //based on the value resolved by promise,
//appropriate template should be returned to parent
}

Films.prototype.getTemplate = async function(){
  //make network call
  //create template based on server response
}

解决方法:

尝试执行aync-await操作.

const ContentPane = function() {}
const Films = function () {}

ContentPane.prototype.getTemplate = async function(){
  let template = `
      <div class="contentPane" id="contentPane">
      ${await new Films().render()}
      </div>
  `;
  return template;
}
Films.prototype.render =  async function(){
  var value =  await this.getTemplate();
  return value;
}
Films.prototype.getTemplate = async function(){
   return new Promise((res, rej) => {
       setTimeout(() => {
           res('123');
        }, 1000);
    });
}
new ContentPane().getTemplate().then(template => {
  console.log(template);
});

标签:ecmascript-6,es6-promise,javascript
来源: https://codeday.me/bug/20191210/2104902.html