等待仅在异步功能中有效

我在 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;

我有一个错误


“等待仅在异步功能中有效”


有什么问题


慕码人2483693
浏览 534回答 3
3回答

慕的地6264312

错误不是指myfunction而是start。async function start() {   ....   const result = await helper.myfunction('test', 'test');}// My functionconst myfunction = async function(x, y) {  return [    x,    y,  ];}// Start functionconst start = async function(a, b) {  const result = await myfunction('test', 'test');    console.log(result);}// Call startstart();我利用这个问题的机会来告诉你一个已知的反模式的使用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 laterasync 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 laterasync function start() {  return myfunction();}// Call start(async() => {  console.log('before start');  await start();    console.log('after start');})();

扬帆大鱼

当我收到此错误时,事实证明我在“异步”函数中调用了map函数,因此此错误消息实际上是指未标记为“异步”的map函数。通过从map函数中取消“ await”调用并提出了一些其他实现预期行为的方法,我解决了这个问题。var myfunction = async function(x,y) {&nbsp; &nbsp; ....&nbsp; &nbsp; someArray.map(someVariable => { // <- This was the function giving the error&nbsp; &nbsp; &nbsp; &nbsp; return await someFunction(someVariable);&nbsp; &nbsp; });}

慕标琳琳

真正的问题是您需要了解异步/等待如何在这里工作。错误在于start function()您需要定义功能Async函数的使用await作为await 使用承诺/未来/任务返回方法/功能async 将方法/功能标记为能够使用等待。Await实际上是在执行promise / resolve的相同过程,并且由于该功能是async其他任务,因此正在并行处理有关更多信息,请参考 MDN DOCSasync function foo(){let myAsyncCall = await .... ('/endpoint') // hitting on some apiconsole.log(myAsyncCall) // myAsyncCall will log out whenever the request get resolved}foo()
打开App,查看更多内容
随时随地看视频慕课网APP