【发布时间】:2018-07-18 19:29:10
【问题描述】:
我正在尝试使用 node.js 的 JIMP 库从磁盘加载两种字体。然后使用加载的字体在图像上打印文本。然而,字体没有及时加载,因为函数是异步的,并继续在图像上写入文本,导致没有写入任何内容。 .then() 中的代码在正确加载字体之前执行
function generateStatsImage(statsJsonObject){
var stats = statsJsonObject;
var mainImage = Jimp.read("./template/StatsTemplate.png")
.then(function(image){
loadedBackground = image;
var ubuntu36whitefont = Jimp.loadFont("./ubuntu36white.fnt");
var ubuntu28whitefont = Jimp.loadFont("./ubuntu28white.fnt");
return (ubuntu36whitefont, ubuntu28whitefont);
})
.then(function(ubuntu36whitefont, ubuntu28whitefont){
image.print(ubuntu28whitefont, 130, 152 , stats.stats.p2.top1.value);
image.print(ubuntu28whitefont, 337, 152 , stats.stats.p10.top1.value);
image.print(ubuntu28whitefont, 542, 152 , stats.stats.p9.top1.value);
image.write("stats.png"); // save
})
.catch(function(err){
console.log("catch error: " + err);
});
};
【问题讨论】:
-
我假设
loadFont是异步的,.. 所以你需要像其他承诺一样处理,..return (ubuntu36whitefont, ubuntu28whitefont);这是什么 Javascript 概念?。 -
不知道您可以返回两个以上的东西,这很容易解决。但是你如何正确处理承诺
-
一个promise只能返回一个值,。这就是为什么我指出该语法,例如。
return (x,y)在 JS 中没有意义,它只会返回 y..
标签: javascript node.js asynchronous