在 promise 上使用 apply() 并且无法访问 promise 响应数据

Using apply() on a promise and not able to access promise response data

我在 returns 承诺的函数上调用 apply 方法,但在调用 apply 方法后获取响应数据时遇到问题。

getData(data) {
    axios.post('/post/something', data)
         .then(res => console.log(res)); // Returns 'Success'
}

callService(args, fn) {
    return fn.apply(this, args)
             .then(() => this.doSomethingElse())
             .then(res => console.log(res)); // Returns undefined
}


callService([1,2], getData);

为什么 fn.apply 包含承诺但不包含从服务器发回的数据?正确的做法是什么?

Why does fn.apply contain a promise but not the data that was sent back from the server?

callService return 是一个解析为 this.doSomethingElse() 的 return 值的承诺,显然是 undefined。当您链接 .then 调用时会发生这种情况。由 .then 编辑的承诺 return 解析为传递给它的函数的 return 值。 You can learn more about promises on MDN.

What is the correct way to do this?

我猜你想要这个:

callService(args, fn) {
    return fn.apply(this, args)
             .then(res => {
                this.doSomethingElse();
                return res;
             });
}

或者如果 doSomethingElse return 是一个承诺:

callService(args, fn) {
    return fn.apply(this, args)
             .then(res => this.doSomethingElse().then(() => res));
}