在诺言数组中的获取请求之间添加超时

时间:2019-07-10 09:34:29

标签: javascript async-await timeout axios es6-promise

干草 我向api发送了大量请求,并且我需要控制请求流

我具有使用axios发出请求并返回promise的功能,然后我对数组进行真实处理并发出请求,然后使用Promise.all()完成请求,而没有任何延迟和控制,其中可以放置一些控制功能来限制请求,然后再将其发送到api

我得到了功能:

        return new Promise((resolve, reject) => {
            console.log(`Getting address for ${lat}, ${lng}...`);
            // Make sure we pass lat,lng to the API.
            axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&result_type=locality&result_type=administrative_area_level_1&result_type=country&key=${apiKey}`)
                .then(response => {
                    return resolve(response)
                })
                .catch(error => {
                    return reject(error.message)
                }).catch(reject => {
                    return reject
                })
        })
    }

然后我将数组设为真并使用get func

const newData = data.map(async item => {
        let results = ''
        let reqStatus = ''
        if (item.Longitude !== "blank") {
            const req = await getAddress(item.Longitude, item.Latitude).catch((error) => {
                console.log(error);
            });
            reqStatus = req.status
            results = req.data
        } else {
            results = 'blank'
        }
        let newItem = ''
        //console.log(JSON.stringify(results, null, 2))
        console.log(`status: ${reqStatus} ${results.status}`)
        if (reqStatus == '200' && results.status == 'OK') {
            const rstlength = results.results[0].address_components.length
            newItem = {
                ...item,
                //results_from_google: results,  //results.results[0].address_components[0].long_name
                address_1: rstlength > 0 ? results.results[0].address_components[0].long_name : 'blank',
                address_2: rstlength > 1 ? results.results[0].address_components[1].long_name : 'blank',
                address_3: rstlength > 2 ? results.results[0].address_components[2].long_name : 'blank',
                address_4: rstlength - 1 > 3 ? results.results[0].address_components[3].long_name : 'blank'
            }

        } else {
            newItem = {
                ...item,
                //results_from_google: results,  //results.results[0].address_components[0].long_name
                address_1: 'blank',
                address_2: 'blank',
                address_3: 'blank',
                address_4: 'blank'
            }
        }

        return newItem;
    })

现在如何延迟请求?

1 个答案:

答案 0 :(得分:0)

您可以尝试: https://www.npmjs.com/package/bottleneck

const limiter = new Bottleneck({
  minTime: 333
});

limiter.schedule(() => myFunction(arg1, arg2))
.then((result) => {
  /* handle result */
});