axios请求立即开始,无需等待axios.all

时间:2019-06-12 08:27:44

标签: javascript promise es6-promise

我的axios承诺无法按预期工作。我猜想执行是在forEach循环内开始的。我希望axios执行仅在batch.commit

之后开始
aMobileNumbers.forEach(function(iMobileNumber) {
    promises.push(axios.post('https://example.com', {
            'app_id' : "XXXXXXX-7595",
            'contents' : { "en":`${sText}` },
        })
        .then((response) => console.log(response.data))
        .catch((response) => console.log(response))
    );
})

console.log(`#${context.params.pushId} Promises: `, promises);

return batch.commit().then(() => {
    console.log(`wrote`);
    return axios.all(promises); //<--- doesnot execute here
})
.then(() => db.doc(`/MGAS/${context.params.pushId}`).delete())
.then(() => console.log(`Deleted the MQ`))
.catch((error) => console.log(`#${context.params.pushId} ${error}`));  

1 个答案:

答案 0 :(得分:2)

调用axios post方法确实会启动请求。如果要在提交后启动请求,则应将代码放在then回调中:

return batch.commit().then(() => {
    console.log(`wrote`);

    var promises = aMobileNumbers.map(function(iMobileNumber) {
        return axios.post('https://example.com', { // <--- does execute here
                'app_id' : "XXXXXXX-7595",
                'contents' : { "en":`${sText}` },
            })
            .then((response) => console.log(response.data))
            .catch((response) => console.log(response));
    })

    console.log(`#${context.params.pushId} Promises: `, promises);

    return axios.all(promises);
})
.then(() => db.doc(`/MGAS/${context.params.pushId}`).delete())
.then(() => console.log(`Deleted the MQ`))
.catch((error) => console.log(`#${context.params.pushId} ${error}`));