Как вернуть значение, возвращаемое функцией, используя обещание? - PullRequest
0 голосов
/ 25 апреля 2019

Я создаю компонент Vue.js, который возвращает HTML-код с помощью метода render ().Структура метода 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);
}

Как вернуть построенный объект "element" или, в качестве альтернативы, я могу "дождаться" выполненияблок «function (jsonFile)» перед его возвратом?

1 Ответ

0 голосов
/ 26 апреля 2019

Попробуйте вернуть элемент из 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); });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...