我的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}`));
答案 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}`));