我一直在 console.log 上收到 Promise { < pending > } ,我对异步功能一点经验都没有。(使用 JavaScript、Node、Mongodb)
function resolveAfter1() {
return new Promise(resolve => {
var scoresFromDb = db.account.find({}, { username: 1, score: 1 }).toArray(function(err, result) {
if (err) throw err;
// return result;
})
setTimeout(() => {
resolve('resolved');
}, 1000);
});
}
async function asyncCall() {
var result = await resolveAfter1();
}
asyncCall();
console.log(asyncCall());
Run Code Online (Sandbox Code Playgroud) 我试图在中调用一个函数ngOnInit()并将其提供两个值。所以这是我试图在内部调用的函数ngOnInit:
this.complexWordIdentification(this.postIWant, this.theHardWords);
这里的问题在于,this.postIWant并且您this.theHardWords正逐渐解决问题,ngOnInit如下所示,这导致了错误。现在,我该如何调用this.complexWordIdentification(this.postIWant, this.theHardWords);并将其输入这些值而又不会出错?
我一直在考虑等待功能吗?但我不知道,对此有何建议?
这是我的ngOnInit:
ngOnInit() {
this.isLoading = true;
this.wordsLoaded = false;
this.postLoaded = false;
this.form = new FormGroup({
annotation: new FormControl(null, {
validators: [
Validators.required,
Validators.minLength(8),
Validators.maxLength(250)
]
})
});
this.id = this.route.snapshot.paramMap.get('postId');
this.annotationService.getWords();
this.annotationSub = this.annotationService
.getWordUpdateListener()
.subscribe((thewords: ComplexWord[]) => {
this.thewords = thewords;
this.thewords.map(word => {
this.theHardWords.push(word.word);
this.wordWithAnnotation.push(word);
});
this.wordsLoaded = true;
this.isLoading = this.postLoaded && this.wordsLoaded;
});
this.postsService.getPosts();
this.postsSub …Run Code Online (Sandbox Code Playgroud) 我一直在尝试在右上角添加图例和/或信息部分以显示有关我突出显示的状态的描述,但我无法这样做,因此我不得不发布一些指导。
我正在使用React 16.13with typescript,所以在这个阶段使用钩子而不是类组件(仍然可以使用,但试图避免它)。我正在使用的库是React-Leaflet. 我一整天都在网上阅读,我无法弄清楚如何将这两件事添加到我的项目中,我想一旦我弄清楚如何做另一个就会很容易实现。
这是我的代码如下:
const App: React.FC = () => {
const [mapCenter, setMapCenter] = useState<L.LatLngTuple>([
36.778259,
-119.417931
]);
const [geoJson, setGeoJson] = useState<TopoJSON[]>([]);
const geoJsonRef = useRef<GeoJSON>(null);
useEffect(() => {
if (data.type === "Topology") {
for (let key in data.objects) {
if (data.objects.hasOwnProperty(key)) {
setGeoJson(topojson.feature(data, data.objects[key]));
}
}
}
}, []);
const highlightFeature = (e: L.LeafletMouseEvent) => {
let layer = e.target;
layer.setStyle({
weight: 5,
color: "#666",
dashArray: "",
fillOpacity: 0.7
}); …Run Code Online (Sandbox Code Playgroud) javascript ×2
angular ×1
asynchronous ×1
ecmascript-6 ×1
geojson ×1
leaflet ×1
mongodb ×1
node.js ×1
reactjs ×1
typescript ×1