我需要一个异步功能才能等待另一个功能
我有2个异步功能 - 一个函数获得城镇的ID,第二个函数占据了这些ID并获得{Towns}对象。我正在进口一个也是异步的API。
第一个功能正常,但是第二个功能返回
log Catchtown [错误:找不到]
代码:
import { getTown, getTownIds } from "./api/towns"
//getting IDs from API
const getTownIdsAsync = async () => {
const asyncids = await getTownIds()
return(asyncids.ids)
}
let idcka = new Promise((resolve, reject) => {
resolve(getTownIdsAsync())
})
.then(result => {
idcka = result
for(i=0; i < idcka.length; i++){
}
})
.catch(err => {
console.log('catchIdcka', err)
})
//getting Towns from API
const getTownsByIdsAsync = async (ajdycka) => {
const asyncTowns = await getTown(ajdycka)
return(asyncTowns)
}
let towns = new Promise((resolve, reject) => {
resolve(getTownsByIdsAsync())
})
.then(result => {
towns = result
console.log(towns)
})
.catch(err => {
console.log('catchTowns', err)
})
I have 2 async functions - one gets ids of towns, and the second one takes these ids and gets {towns} objects. I am importing an API which is also async.
The first function works fine, but the second one returns
LOG catchTowns [Error: Not found]
code:
import { getTown, getTownIds } from "./api/towns"
//getting IDs from API
const getTownIdsAsync = async () => {
const asyncids = await getTownIds()
return(asyncids.ids)
}
let idcka = new Promise((resolve, reject) => {
resolve(getTownIdsAsync())
})
.then(result => {
idcka = result
for(i=0; i < idcka.length; i++){
}
})
.catch(err => {
console.log('catchIdcka', err)
})
//getting Towns from API
const getTownsByIdsAsync = async (ajdycka) => {
const asyncTowns = await getTown(ajdycka)
return(asyncTowns)
}
let towns = new Promise((resolve, reject) => {
resolve(getTownsByIdsAsync())
})
.then(result => {
towns = result
console.log(towns)
})
.catch(err => {
console.log('catchTowns', err)
})
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不知道您如何处理状态,也不知道您是否正在使用类或功能性组件,所以我只举个示例,使用功能组件和挂钩我将如何进行操作。
IDCKA
承诺应在某个时候(可能只是在那里或使用Redux)返回某物并存储其状态。我将只使用状态挂钩在这里。然后,使用效果钩当
iDckavalue 已更改。
这样,我们确保
towns
保证只有在IDCKAVALUE
更改时才能运行。最后,这里有一些关于挂钩的文档。
因此,现在也将效应钩子包裹在第一个功能上。
I don't know how you are handling state nor if you are using class or functional components so I'll just give an example how I'd do it using a functional component and hooks.
The
idcka
promise should return something and store its state at some point, maybe just there or using redux. I'll just use the state hook here.Then, use an effect hook to call the second promise when
idckaValue
has changed.This way, we ensure that the
towns
promise only runs whenidckaValue
changes.And finally here's some documentation about hooks.
So wrapping up now using an effect hook to the first function too.