为了账号安全,请及时绑定邮箱和手机立即绑定

等待仅在异步功能中有效

等待仅在异步功能中有效

慕妹3242003 2019-11-03 08:04:53
我在 lib/helper.jsvar 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;我有一个错误“等待仅在异步功能中有效”有什么问题
查看完整描述

3 回答

?
qq_花开花谢_0

TA贡献1835条经验 获得超7个赞

错误不是指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。


错误


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

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

async function start() {

  return myfunction();

}


// Call start

(async() => {

  console.log('before start');


  await start();

  

  console.log('after start');

})();



查看完整回答
反对 回复 2019-11-04
?
手掌心

TA贡献1942条经验 获得超3个赞

当我收到此错误时,事实证明我在“异步”函数中调用了map函数,因此此错误消息实际上是指未标记为“异步”的map函数。通过从map函数中取消“ await”调用并提出了一些其他实现预期行为的方法,我解决了这个问题。


var myfunction = async function(x,y) {

    ....

    someArray.map(someVariable => { // <- This was the function giving the error

        return await someFunction(someVariable);

    });

}



查看完整回答
反对 回复 2019-11-04
?
qq_笑_17

TA贡献1818条经验 获得超7个赞

真正的问题是您需要了解异步/等待如何在这里工作。错误在于start function()


您需要定义功能Async函数的使用await作为


await 使用承诺/未来/任务返回方法/功能


async 将方法/功能标记为能够使用等待。


Await实际上是在执行promise / resolve的相同过程,并且由于该功能是async其他任务,因此正在并行处理


有关更多信息,请参考 MDN DOCS


async function foo(){


let myAsyncCall = await .... ('/endpoint') // hitting on some api

console.log(myAsyncCall) // myAsyncCall will log out whenever the request get resolved


}


foo()



查看完整回答
反对 回复 2019-11-04
  • 3 回答
  • 0 关注
  • 286 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号