将promise赋值给变量,再用变量.then方法处理成功的操作,可以吗?

将promise赋值给变量,再用变量.then方法处理成功的操作,可以吗?
代码
let resp;
if(edit_ID){
  resp = this.$axios.put(`/api/seach/list/${edit_ID}`,data);
}else{
  resp = this.$axios.post('/api/seach/list/',data);
}

 resp.then(res=>{
  console.log('success');
})
res.catch(err=>{
  console.log('error')
})

运行结果及报错内容

代码没有放在async await 里,会不会出现问题?

我的解答思路和尝试过的方法
我想要达到的结果

根据edit_ID来判断是新建还是编辑,然后选择对应的接口;然后在成功回调里的代码,都是一样的,能不能就是当到一起,

会出问题的,你不能这样去写,因为本身 promise 是一个异步函数,你如果不采用 generator 或者 async 方式转换代码同步的话,你是不能直接去用 变量接收值得,resp 不写 await 默认是一个异步promise 得到的结果就是空,空肯定是没有.then方法的,你如果不想用 async/await 这种方式的话,可以采用以下方式 函数retrun的方式进行改写

resp(){
  if(edit_ID){
    return this.$axios.put(`/api/seach/list/${edit_ID}`,data);
  }else{
    return this.$axios.post('/api/seach/list/',data);
  }
}

// 调用位置
this.resp().then(res=>{
  console.log('success');
}).catch(err=>{
  console.log('error')
})


可以这样写,put,post返回的是promise,直接加then、catch么问题

只是要改下,then需要同时传递成功失败二个回调函数或者链式调用catch,而不是catch单独另起一行【虽然出错后可以执行】,ajax操作有问题控制台会抛出**Uncaught (in promise) Error:**错误,虽然添加了catch回调

但是不用await/async,如果需要ajax返回值,注意需要通过回调来获取数据。


    resp.then(res => {
        console.log('success');
    },
err => {
        console.log('error');

    })

或者这样

    resp.then(res => {
        console.log('success');
    }).catch(err => {
        console.log('error')
    })

img

用return Promise哦