javascript - 在 Promise 上使用 apply() 且无法访问 Promise 响应数据

标签 javascript es6-promise axios

我正在对返回 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/

相关文章:

php - 按下重置按钮后通过关闭旧弹出窗口显示新的弹出窗口并重新显示相同的表单

javascript - 节点坚持认为这些字符串不相同

javascript - 返回函数供进一步使用,但不存储旧结果

javascript - .then() 在 Promise.all() 之前执行

javascript - 如何在我的 html 编辑器中删除 ace 编辑器的第一个文档类型工具提示?

javascript - 如何使用 Expo 在 React-Native 应用程序上顺序运行异步函数

javascript - 在不同的文件/函数中捕获 axios 请求

reactjs - 如何返回axios的响应作为返回

reactjs - 无法使用 axios 读取未定义的属性 `.then` 并在操作中使用react

javascript - 如何模拟 axios.create([config]) 函数以返回其实例方法而不是用模拟覆盖它们?