在Vue 2中使用Axios呼叫承诺

时间:2017-12-06 19:15:53

标签: vue.js vuejs2 axios

如何在此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);
    });

这个包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);
}));

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

1 个答案:

答案 0 :(得分: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;
        });
}));

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

 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
         }
       })
     });
   });
 });

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