[英]async not waiting for await in callback to finish
Im still a rookie with async and awaits, but this is what Im working with. 我仍然是异步的新手,正在等待,但这就是我正在使用的。
async function _getImageURLs(folder) {
if (!id) return;
foo.AWSS3Helper.GetImageUrls(so, function (imageUrls) {
return await imageUrls;
});
}
The fuction _getImageURLs() is still returning without waiting for the AWSS3Helper.GetImageUrls finishes. 功能_getImageURLs()仍在返回,而无需等待AWSS3Helper.GetImageUrls完成。 Im guessing it has something to do with being inside a callback function. 我想这与在回调函数内部有关。 Does the callback need to be async as well? 回调也需要异步吗?
Use await on the function not on the return statement 在函数上而不是在return语句上使用await
async function _getImageURLs(folder) { if (!id) return; foo.AWSS3Helper.GetImageUrls(so, await function (imageUrls) { return imageUrls; }); }
Try it with observables. 尝试使用可观察的东西。 Something like this... 像这样
function _getImageURLs(folder) {
if (!id) return;
const imageUrlObservable = of(foo.AWSS3Helper
.GetImageUrls(so, function (imageUrls) {
return imageUrls;
})
);
imageUrlObservable.subscribe({
next(imageUrL) { console.log(imageUrL) },
complete() { console.log('Finished sequence'); }
});
}
As far as i see there are no promises here, you have a callback based mechanism on the api so using async/await
seems pointless 据我所见,这里没有任何承诺,您在api上有基于回调的机制,因此使用async/await
似乎毫无意义
you should pass a callback to the method and invoking it as soon as you have the result available 您应该将回调传递给该方法,并在获得结果后立即调用它
function _getImageURLs(folder, callback) {
if (!id) callback();
foo.AWSS3Helper.GetImageUrls(so, function (imageUrls) {
callback(imageUrls);
});
}
_getImageURLs("somefolder", function(result) {
console.log(result);
// do whatever you want here with the result
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.