在Vue 2中使用Axios呼叫承诺

use*_*734 1 vue.js axios vuejs2

如何在此Vios-Snotify的Axios POST请求中实现Promise?这是我的Axios帖子请求:

const url = 'https://foobar.api/photos';
axios.post(url, {photo: "data:image/jpeg;base64," + photo})
    .then(function (response) {
        console.info('Done');
    })
    .catch(function (error) {
        console.error(error);
    });
Run Code Online (Sandbox Code Playgroud)

这个包Vue-Snotify我想添加一个通知器,它将显示一个带有显示进度的加载器的通知框.这是关于文档应该是什么样子:

this.$snotify.async('Called with promise', 'Success async', () => new Promise((resolve, reject) => {
  setTimeout(() => resolve({
    title: 'Success!!!',
    body: 'We got an example success!',
    config: {
      closeOnClick: true
    }
  }), 2000);
}));
Run Code Online (Sandbox Code Playgroud)

但是如何实现这一目标呢?我不是Vue的专业人士,也无法弄清楚如何将这两者结合起来.

Edu*_*uad 5

您可以返回axios来完成此操作,但如果您发现错误,Snotify将显示成功消息.试试这个:

this.$snotify.async('Called with promise', 'Success async', () => {
    const url = 'https://foobar.api/photos';
    return axios.post(url, {photo: "data:image/jpeg;base64," + photo})
        .then(function (response) {
            console.info('Done');
        })
        .catch(function (error) {
            // handle error first

            throw error;
        });
}));
Run Code Online (Sandbox Code Playgroud)

编辑:如果你想控制消息到这个:

 this.$snotify.async('Called with promise', 'Success async', () => {
   return new Promise((resolve, reject) => {
     const url = 'https://foobar.api/photos';
     return axios.post(url, {photo: "data:image/jpeg;base64," + photo})
     .then(function (response) {
       resolve({
         title: 'Success!!!',
         body: 'We got an example success!',
         config: {
           closeOnClick: true
         }
       })
     })
     .catch(function (error) {
       reject({
         title: 'Error!!!',
         body: 'We got an example error!',
         config: {
           closeOnClick: true
         }
       })
     });
   });
 });
Run Code Online (Sandbox Code Playgroud)

小提琴:https: //jsfiddle.net/qo6fdv1n/2/