我希望函数执行X(= 3)次直到成功。
我知道这个问题看起来与this question类似,但是所有答案都无济于事。
我只想将此消息发送为松弛状态,如果失败,请重试3次。
const options = {
'text': 'Hello'
}
let flag = 0
function sendMessage () {
const promise = new Promise((resolve, reject) => {
axios.post(webhookURL, JSON.stringify(options))
.then(response => {
flag++
return resolve('SUCCESS: Sent slack webhook', response.data)
})
.catch(error => {
return reject(new Error('FAILED: Sent slack webhook', error))
})
})
return promise
}
for (let maxRetry = 0; maxRetry < 3; maxRetry++) {
const p = sendMessage()
p
.then((status) => {
console.log(status)
})
.catch((err) => {
console.log(err)
})
console.log('flag', flag)
if (flag >= 1) {
break
}
}
即使成功,它也会运行3次。承诺工作不正常 输出
flag 0
flag 0
flag 0
SUCCESS: Sent slack webhook
SUCCESS: Sent slack webhook
SUCCESS: Sent slack webhook
我是nodejs的新手。如果你们中的任何人都可以在这里帮助我,将会非常有帮助。
答案 0 :(得分:2)
有一个使用async/await
功能的解决方案,这将使您可以等待对诺言的解析,然后再运行对异步函数的另一次调用
成功示例:
//const axios = require('axios');
function sendMessage() {
return new Promise((resolve, reject) => {
axios
.get('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
resolve('SUCCESS: Sent slack webhook', response.data);
})
.catch(error => {
reject(new Error('FAILED: Sent slack webhook', error));
});
});
}
(async function loop() {
for (let i = 0; i < 3; i++) {
console.log('loop count = ', i);
try {
const res = await sendMessage();
console.log(res);
break;
} catch (error) {
console.log(error);
}
}
})();
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
错误示例:
//const axios = require('axios');
function sendMessage() {
return new Promise((resolve, reject) => {
axios
.get('https://falseurl')
.then(response => {
resolve('SUCCESS: Sent slack webhook', response.data);
})
.catch(err => {
console.log('FAILED: Sent slack webhook')
reject(new Error('FAILED: Sent slack webhook', err));
});
});
}
(async function loop() {
for (let i = 0; i < 3; i++) {
console.log('loop count = ', i);
try {
const res = await sendMessage();
console.log(res);
break;
} catch (err) {
console.log(err);
}
}
})();
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>