【问题标题】:Calling Promise with Axios in Vue 2在 Vue 2 中使用 Axios 调用 Promise
【发布时间】:2018-05-20 18:45:55
【问题描述】:

如何在这个 Vue-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 的专业人士,不知道如何将这两者结合起来。

【问题讨论】:

    标签: vue.js vuejs2 axios


    【解决方案1】:

    您可以返回 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/

    【讨论】:

    • 不错!有没有办法在一段时间后删除通知器?文档不谈论它@eduardo-aguad
    • @user1469734 我在文档中找到了timeout 配置。在配置中尝试此设置timeout: 1000;,并删除closeOnClick
    • @EduardoAguad 嗨!成功或错误时我该怎么做?我尝试在解决之前使用我的 vue 函数,但出现错误。
    • @autumnrustle axios 返回一个承诺,您可以使用该承诺处理错误和成功。 developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
    猜你喜欢
    • 2020-03-08
    • 2019-12-04
    • 1970-01-01
    • 1970-01-01
    • 2018-07-08
    • 2019-06-12
    • 1970-01-01
    • 2018-06-05
    • 1970-01-01
    相关资源
    最近更新 更多