Node.js:如何等待Promise函数赋值完成后执行后续代码
解决方案
一、让后续代码等待赋值完成
因为qrRun是异步函数,调用它会返回一个Promise,你只需要在stuff里用await等待它的执行结果,同时把stuff也改成异步函数即可:
async function stuff(image) { // 用await等待qrRun执行完成,拿到实际扫描结果 var scannedCode = await qrRun(image); console.log("I want to console.log scannedcode and it be the actual thing completed", scannedCode); }
如果没办法把stuff改成异步函数(比如它是某个同步回调的处理函数),也可以用Promise的.then()方法处理:
function stuff(image) { qrRun(image).then(scannedCode => { console.log("I want to console.log scannedcode and it be the actual thing completed", scannedCode); // 所有依赖scannedCode的后续代码都要写在这个回调里 }).catch(err => { // 处理扫描过程中可能出现的错误 console.error(err); }); }
二、移除qrRun里的Promise(不破坏原有功能)
qrRun里的Promise是用来把QRReader的回调风格API转换成Promise风格的,要移除它的话,直接把qrRun改回回调风格的函数就行:
// 改成接受回调参数的函数,放弃async/await语法糖 function qrRun(image, callback) { jimp.read(fs.readFileSync(image), (err, img) => { if (err) { callback(err); return; } const qr = new QRReader(); qr.callback = (decodeErr, v) => { if (decodeErr) { callback(decodeErr); } else { console.log(v.result); callback(null, v.result); } }; qr.decode(img.bitmap); }); } // 调用时传入回调函数处理结果 function stuff(image) { qrRun(image, (err, scannedCode) => { if (err) { console.error(err); return; } console.log("I want to console.log scannedcode and it be the actual thing completed", scannedCode); }); }
这种方式只是回到了传统的回调模式,功能和原来的qrRun完全一致,只是调用方式发生了变化。
内容的提问来源于stack exchange,提问作者blueberrr
相关产品推荐
相关产品推荐

