我写了这段代码 lib/helper.js
lib/helper.js
var myfunction = async function(x,y) { .... reutrn [variableA, variableB] } exports.myfunction = myfunction;
然后我尝试在另一个文件中使用它
var helper = require('./helper.js'); var start = function(a,b){ .... const result = await helper.myfunction('test','test'); } exports.start = start;
我有一个错误
“等待仅在异步功能中有效”
有什么问题
错误不是指myfunction而是start。
myfunction
start
async function start() { .... const result = await helper.myfunction('test', 'test'); }
// My function const myfunction = async function(x, y) { return [ x, y, ]; } // Start function const start = async function(a, b) { const result = await myfunction('test', 'test'); console.log(result); } // Call start start();
我利用这个问题的机会来告诉你一个已知的反模式的使用await方法:return await。
await
return await
错误
async function myfunction() { console.log('Inside of myfunction'); } // Here we wait for the myfunction to finish // and then returns a promise that'll be waited for aswell // It's useless to wait the myfunction to finish before to return // we can simply returns a promise that will be resolved later // useless async here async function start() { // useless await here return await myfunction(); } // Call start (async() => { console.log('before start'); await start(); console.log('after start'); })();
正确
async function myfunction() { console.log('Inside of myfunction'); } // Here we wait for the myfunction to finish // and then returns a promise that'll be waited for aswell // It's useless to wait the myfunction to finish before to return // we can simply returns a promise that will be resolved later // Also point that we don't use async keyword on the function because // we can simply returns the promise returned by myfunction function start() { return myfunction(); } // Call start (async() => { console.log('before start'); await start(); console.log('after start'); })();
另外,要知道有一个return await正确且重要的特殊情况:(使用try / catch)