如何使用promise返回函数返回的值?

问题描述 投票:0回答:1

我正在创建一个Vue.js组件,它使用render()方法返回html代码。 render()方法的结构是代码中显示的结构。

render: function (h, context) {
   // Element returned by the render function
   var element;

    // .... code that performs initializations

   // The invocation of a promise that downloads a json file
   var promise = loadJsonFile (pathFile);

   promise.then (
       // on success
       function (jsonFile) {
         // ... here is some code that builds an element as 
         // a function of json file contents
         element = buildComponent (jsonFile, h, context);
       },

       // on error
       function (error) {
          console.log(error);
       }
   );

    // Then the variable element returns "nothing"
    return (element);
}

如何返回构造的“元素”对象,或者,在我返回之前,我可以“等待”执行“function(jsonFile)”块吗?

javascript promise
1个回答
0
投票

尝试从buildComponent返回元素并使用另一个then方法等待结果:

render: function (h, context) {
   // Element returned by the render function
   var element;

    // .... code that performs initializations

   // The invocation of a promise that downloads a json file
   var promise = loadJsonFile (pathFile);

   promise.then (
       // on success
       function (jsonFile) {
         // ... here is some code that builds an element as 
         // a function of json file contents
         // return the result of 'buildComponent', throwing another promise
         //     which can be caught with another then statement below
         return buildComponent (jsonFile, h, context);
       },

       // on error
       function (error) {
          console.log(error);
       }
   )
   .then(function(element) {
      // do things with 'element'
   })
   // catch any massive explosions (errors)
   .catch(function(error) { console.log(error); });
}
© www.soinside.com 2019 - 2024. All rights reserved.