使用 Api 调用 Exsport 函数,然后将其导入另一个页面并等待数据
Exsport function with Api call then import it on another page and wait for data
我是新手 export
, import
, async
所以请多多包涵。
我有一个文件,我在其中 API 调用并导出该函数,以便它可以在其他页面上使用。
当然在调用函数时在其他页面上还没有数据有效负载,所以我无法找到。所以我尝试实现 async
(第一次)。
如果这甚至可能,请纠正我,或者我需要一些其他方法。
app.js:
export function inboxMeniIkona () {
//let req = xxxx
fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return new Promise(resolve => {
return data // data here is allright
});
})
.catch(error => console.error('FETCH ERROR:', error))
}
然后我在其他页面上尝试:
import { inboxMeniIkona } from '~/app'
async function asyncCall() {
console.log('calling');
const result = await inboxMeniIkona();
console.log(result);
// expected output: "resolved"
}
asyncCall();
我还在
CONSOLE LOG: calling
CONSOLE LOG: undefined
请指教
在你的函数中添加 async 并在你的 fetch 中等待,return 就像这样。
export async function inboxMeniIkona () {
//let req = xxxx
return await fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return data // data here is allright
})
.catch(error => console.error('FETCH ERROR:', error))
}
我是新手 export
, import
, async
所以请多多包涵。
我有一个文件,我在其中 API 调用并导出该函数,以便它可以在其他页面上使用。
当然在调用函数时在其他页面上还没有数据有效负载,所以我无法找到。所以我尝试实现 async
(第一次)。
如果这甚至可能,请纠正我,或者我需要一些其他方法。
app.js:
export function inboxMeniIkona () {
//let req = xxxx
fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return new Promise(resolve => {
return data // data here is allright
});
})
.catch(error => console.error('FETCH ERROR:', error))
}
然后我在其他页面上尝试:
import { inboxMeniIkona } from '~/app'
async function asyncCall() {
console.log('calling');
const result = await inboxMeniIkona();
console.log(result);
// expected output: "resolved"
}
asyncCall();
我还在
CONSOLE LOG: calling
CONSOLE LOG: undefined
请指教
在你的函数中添加 async 并在你的 fetch 中等待,return 就像这样。
export async function inboxMeniIkona () {
//let req = xxxx
return await fetch(req)
.then(response => {
if (response.ok) {
return response.json()
} else {
throw new Error('NETWORK RESPONSE ERROR')
}
})
.then(data => {
return data // data here is allright
})
.catch(error => console.error('FETCH ERROR:', error))
}