首页 > 解决方案 > 异步等待节点js

问题描述

我正在使用节点 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

解决方案


您正在将函数分配给代码末尾的变量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);
});

推荐阅读