我正在尝试传递回调函数作为获取的参数。但我不知道当 api.js 中的 fetch 完成时如何从 index.js 运行回调本身。
index.js
import Api from './Api'
Api.post(callback)
API.js
class Api {
constructor () {}
static post(callback) {
let url 'dummy';
let data = {
id: 2
}
let request = new Request(url, {
method: 'POST',
body: data,
header: new Headers()
})
fetch(request)
.then(function() {
console.log(request);
})
}
}
export default Api;
最佳答案
您可以在.then()
中调用回调函数:
class Api {
static post (callback) {
const request = /* ... */;
fetch(request)
.then(response => response.json())
.then(result => callback(result)); // if you have a result
}
}
...但是你为什么要这么做呢?尝试返回一个 promise 并履行该 promise 。这就是 Promise(以及 fetch API)的意义所在。
class Api {
static post () {
const request = /* ... */;
return fetch(request)
.then(response => response.json());
}
}
// usage:
Api.post().then(callback);
关于javascript - 回调函数作为 fetch 中的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47814924/