admin管理员组文章数量:1426342
I'm trying to pass in a callback function as an argument to fetch. But i dont know how to run the callback itself from index.js when fetch is plete in api.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;
I'm trying to pass in a callback function as an argument to fetch. But i dont know how to run the callback itself from index.js when fetch is plete in api.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;
Share
Improve this question
edited Dec 14, 2017 at 13:53
SALEH
1,5621 gold badge14 silver badges22 bronze badges
asked Dec 14, 2017 at 13:48
user2952238user2952238
7872 gold badges14 silver badges37 bronze badges
1
-
Functions are always called with
()
. I.e.callback()
. – Felix Kling Commented Dec 14, 2017 at 15:05
2 Answers
Reset to default 4You can call your callback function in a .then()
:
class Api {
static post (callback) {
const request = /* ... */;
fetch(request)
.then(response => response.json())
.then(result => callback(result)); // if you have a result
}
}
... but why would you do that? Try to return a promise and work with that promise. This is what promises (and the fetch API) are about.
class Api {
static post () {
const request = /* ... */;
return fetch(request)
.then(response => response.json());
}
}
// usage:
Api.post().then(callback);
You can simply call the callback in the then
callback:
fetch(request)
.then(function() {
console.log(request);
callback();
})
Or chain it:
fetch(request)
.then(function() {
console.log(request);
}).then(callback);
本文标签: javascriptCallback func as parameter in fetchStack Overflow
版权声明:本文标题:javascript - Callback func as parameter in fetch - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745428998a2658244.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论