gpt4 book ai didi

javascript - 回调函数作为 fetch 中的参数

转载 作者:行者123 更新时间:2023-12-01 02:37:13 24 4
gpt4 key购买 nike

我正在尝试传递回调函数作为获取的参数。但我不知道当 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com