【问题标题】:Async Await Node js异步等待节点js
【发布时间】:2018-05-14 15:17:28
【问题描述】:

我正在学习使用 node js 的异步等待

var testasync = async () =>
{

const result1 = await returnone();

return result1;
}

testasync().then((name)=>{
    console.log(name);
}).catch((e) =>{
    console.log(e);
});


var returnone = () =>{
    return new Promise((resolve,reject)=>
{
    setTimeout(()=>{
        resolve('1');
    },2000)
})
}

它失败了,returnone is not a function。我究竟做错了什么?单独调用函数工作

returnone().then((name1) => {
    console.log(name1)
})

只要调用上面的代码就可以了

【问题讨论】:

标签: node.js


【解决方案1】:

由于hoisting,您收到此错误的原因。你的 JS 看到的代码应该是这样的

var returnone;
var testasync = async () => {
  const result1 = await returnone();  
  return result1;
}

testasync().then((name) => {
  console.log(name);
}).catch((e) => {
  console.log(e);
});

returnone = () => {
  return new Promise((resolve,reject) => {
    setTimeout(() => {
      resolve('1');
    }, 2000)
  })
}

所以returnone 的值是未定义的。

【讨论】:

    【解决方案2】:

    您正在将函数分配给代码末尾的变量returnone,但您试图在此分配之前调用该函数。修复代码有两种选择:

    选项 1

    使用函数声明;这样,函数就被提升了,你可以从一开始就使用它:

    var testasync = async () => {
      const result1 = await returnone();  
      return result1;
    }
    
    testasync().then((name) => {
      console.log(name);
    }).catch((e) => {
      console.log(e);
    });
    
    function returnone() {
      return new Promise((resolve,reject) => {
        setTimeout(() => {
          resolve('1');
        }, 2000)
      })
    }
    

    选项 2

    在尝试调用之前将函数分配给变量:

    var returnone = () => {
      return new Promise((resolve,reject) => {
        setTimeout(() => {
          resolve('1');
        }, 2000)
      })
    }
    
    var testasync = async () => {
      const result1 = await returnone();  
      return result1;
    }
    
    testasync().then((name) => {
      console.log(name);
    }).catch((e) => {
      console.log(e);
    });
    

    【讨论】:

    • 有道理,我只是想重写一些,忘记了函数的定义是在调用之后
    猜你喜欢
    • 1970-01-01
    • 2017-01-24
    • 2016-12-26
    • 2018-10-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-17
    • 2018-12-30
    • 1970-01-01
    相关资源
    最近更新 更多