- 通過傳入回調函數的方式
function api(url, callback) {
fetch(url)
.then(res => res.json())
.then(res => {
callback(res)
})
}
function callback(res) {
console.log('res', res);
}
api('你的接口url', callback);
- 通過異步函數的方式(這裡要注意的是兩個函數都要使用async)
async function testAsync() {
let res = await new Promise(resolve => {
fetch('你的接口url')
.then(res => res.json())
.then(res => {
resolve(res);
})
})
console.log(res);
let res1 = await new Promise(resolve => {
fetch('你的接口url')
.then(res => resolve(res.json()))
})
console.log(res1);
}
testAsync();