我试图从foreach循环中的回调函数中获取数据,但它似乎无法正常工作,因为循环在调用回调函数之前结束。以下是我的功能:
function convertImgToBase64URL(url, callback, outputFormat) {
var img = new Image();
img.crossOrigin = 'Anonymous';
img.onload = function () {
var canvas = document.createElement('CANVAS'),
ctx = canvas.getContext('2d'), dataURL;
canvas.height = img.height;
canvas.width = img.width;
ctx.drawImage(img, 0, 0);
dataURL = canvas.toDataURL(outputFormat);
callback(dataURL);
canvas = null;
};
img.src = url;
}
我调用这个函数的代码如下:
angular.forEach(alarms, function (alarm) {
convertImgToBase64URL(alarm.photo, function (base64Img) {
alarmInfo.push({
severity: alarm.payload.severity,
from: alarm.name,
location: alarm.location,
alarmTime: alarm.time,
photo: base64Img,
contextId: alarm.id
});
$log.info(base64Img);
});
});
有没有办法让循环等待回调函数完成,然后继续循环?
暂无答案!
目前还没有任何答案,快来回答吧!