我正在对返回 Promise 的函数调用 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 包含 promise 但不包含从服务器发回的数据?正确的做法是什么?
最佳答案
Why does fn.apply contain a promise but not the data that was sent back from the server?
callService
返回一个 promise ,该 promise 解析为 this.doSomethingElse()
的返回值,该值显然是未定义
。这就是当您链接 .then
调用时会发生的情况。 .then
返回的 Promise 解析为传递给它的函数的返回值。 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
返回一个 promise :
callService(args, fn) {
return fn.apply(this, args)
.then(res => this.doSomethingElse().then(() => res));
}
关于javascript - 在 Promise 上使用 apply() 且无法访问 Promise 响应数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46737591/