我正在尝试学习异步/等待。我想等待异步函数中的return语句。我必须多次调用它,所以我在内部使用了setTiemout。
编辑:
package com.xenoterracide.gradle.alignmentrules;
import org.gradle.api.artifacts.ComponentMetadataContext;
import org.gradle.api.artifacts.ComponentMetadataDetails;
import org.gradle.api.artifacts.ComponentMetadataRule;
import java.util.Objects;
public class ImmutablesAlignmentRule implements ComponentMetadataRule {
@Override
public void execute( ComponentMetadataContext ctx ) {
ComponentMetadataDetails details = ctx.getDetails();
String group = "org.immutables";
details.allVariants( vm -> {
if ( Objects.equals( details.getId().getGroup(), group ) ) {
details.belongsTo( group + ":platform:2.+", true );
}
} );
}
}
我已经尝试过org.immutables:value
,但是它在第一次调用该函数后立即触发。我如何等待退货?
答案 0 :(得分:2)
永远不要从异步(非承诺)回调或inside the new Promise
constructor中调用承诺返回函数,例如getPictureR
。您也从未解决过new Promise
。您正在寻找
return new Promise((resolve, reject) => {
setTimeout(resolve, 1 * 1000/2);
}).then(() => {
return getPictureR(); // do the promise call in a `then` callback to properly chain it
})
但是,由于您使用的是async
/ await
,因此无论如何都不需要递归函数和then
链。另外,您还可以在单独的帮助函数中排除setTimeout
承诺式换行:
function delay(t) {
return new Promise(resolve => setTimeout(resolve, t));
}
async function somefunction() {
while (true)
/* some code */
const prev = $('.actions > .prev', html);
if (prev.length) {
older = prev[0].attribs.href;
} else {
console.log('return');
break;
}
/* some code */
await delay(1 * 1000/2);
// ^^^^^^^^^^^
}
console.log('getPicture done');
}