问题
I'm trying to convert a function that uses promise (and polling) to an async function, but I'm not really sure how it works.
I have this:
function myFunction() {
return new Promise(resolve => {
// stuff here ...
var poll = setInterval(function() {
if (condition) {
clearInterval(poll);
resolve("done");
}
}, 100);
});
}
.. but I'm unsure what to await
here:
async function myFunction() {
// stuff here ...
var poll = setInterval(function() {
if (condition) {
clearInterval(poll);
// await what?
}
}, 100);
}
回答1:
setInterval
does not play nice with async await. It is best to use a 'promisified' version of setTimeout that you call again on each iteration of the loop.
const myFunction = async = () => {
let condition = false;
while (!condition) {
await new Promise(resolve => setTimeout(resolve, 100));
condition = processCondition();
}
}
回答2:
async function myFunction() {
// stuff here ...
var poll = await setInterval(function() {
if (condition) {
clearInterval(poll);
// await what?
}
}, 100);
}
来源:https://stackoverflow.com/questions/57213034/promise-to-async-await-when-polling