我编写了一个nodejs函数来对qrcode进行编码,并希望将结果返回给调用者函数,以创建json响应。但是我不知道为什么它不能返回数据响应。我的代码有什么问题。你能帮我吗?
Navigate
我要创建的json响应
OnActivated
答案 0 :(得分:0)
QRCode.toDataURL
使用回调函数(一旦异步检索到url,它将使用参数调用回调函数,因此您不能直接返回它。)
但是,如果不指定回调,它将返回Promise。您可以返回Promise,并在Promise上使用then
方法来获取值。
gen_qrcode : function() {
var QRCode = require('qrcode');
var qr_url = "https://www.google.com";
return QRCode.toDataURL(qr_url, { errorCorrectionLevel: 'M' });
}
//other function
object_name.gen_qrcode().then((url) => {
let json_object = JSON.stringify({
status: 1,
description: 'Success',
qr_data: url
})
console.log(json_object); //do something with json_object
})
或者,您可以将Async / Await(browser support)与指令here.一起使用