node.js - 异步等待节点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)
})
只需调用上面的代码即可
解决方案
您正在将函数分配给代码末尾的变量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);
});
推荐阅读
- windows-10-universal - Xamarin Form - 如何在 UWP 中使 UI 响应
- javascript - 如何改变状态?
- python - 在 Python 中格式化 JSON 数据
- android - 您如何通过即时应用程序中的意图共享图像?
- visual-studio - 使用 Visual Studio 处理源代码中的制表符或空格的默认设置?
- python-3.x - Python 数组舍入
- php - 如何使用php将日期插入mysql查询?
- python - PyTorch 二进制分类 - 相同的网络结构,“更简单”的数据,但性能更差?
- angular - 如何防止垫子扩展面板关闭?
- php - 做对了一切之后,Laravel 没有安装