循环异步后返回数组

时间:2020-02-20 15:20:54

标签: javascript node.js promise

我知道我的问题的解决方案是promise,但我根本不了解如何将其应用于我想做的事情...您能否在不介绍javascript中关于promise的课程的情况下帮助我?

谢谢你

Users and permissions

我只想返回'allresult'... 谢谢您的帮助

1 个答案:

答案 0 :(得分:2)

您无法真正兑现承诺,而是可以像这样解决它:

function getPosition(workers) {
    return Promise.all(workers.map(worker => {
        const {firstname, lastname, address: {streetname, city, country}} = worker;
        return axios.get(`https://api-adresse.data.gouv.fr/search/?q=${streetname} ${city}`)
            .then(response => {
                const [lon, lat] = response.data.features[0].geometry.coordinates;
                return {
                    firstname: firstname,
                    lastname: lastname,
                    address: {streetname, country, city, lon, lat}
                };
            })
            .catch(logger.error)
    })).then(results => results.filter(Boolean));
}

并以

的形式访问结果
getPosition(workers)
    .then(allResults => {
        // do what you need with the results
    })

或者使用async / await语法

(async ()=>{
    const allResults = await getPosition(workers)
    // do what you need with the results
})()