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

等待仅在异步功能中有效

等待仅在异步功能中有效

慕码人2483693 2019-10-12 09:50:26
我在 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 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

错误不是指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-10-12
?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

当我收到此错误时,事实证明我在“异步”函数中调用了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-10-12
?
慕标琳琳

TA贡献1830条经验 获得超9个赞

真正的问题是您需要了解异步/等待如何在这里工作。错误在于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-10-12
  • 3 回答
  • 0 关注
  • 496 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信