我需要一个异步功能才能等待另一个功能

发布于 2025-02-08 17:50:45 字数 939 浏览 2 评论 0原文

我有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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

§对你不离不弃 2025-02-15 17:50:45

我不知道您如何处理状态,也不知道您是否正在使用类或功能性组件,所以我只举个示例,使用功能组件和挂钩我将如何进行操作。

IDCKA承诺应在某个时候(可能只是在那里或使用Redux)返回某物并存储其状态。我将只使用状态挂钩在这里。

const [idckaValue, setIdckaValue] = useState([])

// call idcka promise and store result by using the above setter setIdckaValue()...

然后,使用效果钩iDckavalue 已更改。

useEffect(() => {
    // call towns promise...
}, [idckaValue])

这样,我们确保towns保证只有在IDCKAVALUE更改时才能运行。

最后,这里有一些关于挂钩的文档


因此,现在也将效应钩子包裹在第一个功能上。

import React, { useState, useEffect } from 'react';

function Example() {
    // The state hook to store idcka value, I'm assuming it's an array here.
    const [idckaValue, setIdckaValue] = useState([]);

    // Your getTownIdsAsync function.
    const getTownIdsAsync = async () => {
        const asyncids = await getTownIds()
        return(asyncids.ids)
    }

    // Your getTownsByIdsAsync function.
    const getTownsByIdsAsync = async (ajdycka) => {
        const asyncTowns = await getTown(ajdycka)
        return(asyncTowns)
    }

    // This hook will only run once because its second argument is an empty array.
    useEffect(() => {
        // Getting IDs from API.

        getTownIdsAsync()
            .then(result => {
                // Let's assume you do something with the data and that the result of it is an array.
                setIdckaValue(result)
            })
            .catch(error => {
                console.log('catchIdcka', error)
            })
    }, []);

    // This hook will only run every time idckaValue changes, note its second argument value.
    useEffect(() => {
        // Getting Towns from API

        getTownsByIdsAsync()
            .then(result => {
                // Then you do what you want with result, maybe store it in state and then use it in the render?
                console.log(towns)
            })
            .catch(error => {
                console.log('catchTowns', error)
            })
    }, [idckaValue]);

    return (
        // Your render.
    );
}

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.

const [idckaValue, setIdckaValue] = useState([])

// call idcka promise and store result by using the above setter setIdckaValue()...

Then, use an effect hook to call the second promise when idckaValue has changed.

useEffect(() => {
    // call towns promise...
}, [idckaValue])

This way, we ensure that the towns promise only runs when idckaValue changes.

And finally here's some documentation about hooks.


So wrapping up now using an effect hook to the first function too.

import React, { useState, useEffect } from 'react';

function Example() {
    // The state hook to store idcka value, I'm assuming it's an array here.
    const [idckaValue, setIdckaValue] = useState([]);

    // Your getTownIdsAsync function.
    const getTownIdsAsync = async () => {
        const asyncids = await getTownIds()
        return(asyncids.ids)
    }

    // Your getTownsByIdsAsync function.
    const getTownsByIdsAsync = async (ajdycka) => {
        const asyncTowns = await getTown(ajdycka)
        return(asyncTowns)
    }

    // This hook will only run once because its second argument is an empty array.
    useEffect(() => {
        // Getting IDs from API.

        getTownIdsAsync()
            .then(result => {
                // Let's assume you do something with the data and that the result of it is an array.
                setIdckaValue(result)
            })
            .catch(error => {
                console.log('catchIdcka', error)
            })
    }, []);

    // This hook will only run every time idckaValue changes, note its second argument value.
    useEffect(() => {
        // Getting Towns from API

        getTownsByIdsAsync()
            .then(result => {
                // Then you do what you want with result, maybe store it in state and then use it in the render?
                console.log(towns)
            })
            .catch(error => {
                console.log('catchTowns', error)
            })
    }, [idckaValue]);

    return (
        // Your render.
    );
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文