问题描述
我有 2 个文件用于编写 JS:学习和测试。在学习时,我正在尝试创建一个 asyc 函数,该函数将执行以下操作:
开发一个名为“qAsync
”的“函数声明”
返回一个由两个键组成的对象(通过构造函数构建):
- ‘
doAsync
’:函数:返回setTimeout
函数,可以使用 async/await 语法 - ‘
exec
’:使用doAsync
函数在 11.5 秒后打印某些内容的函数 - ‘
desc
’ : string:描述 doAsync/exec() 正在做什么以及如何使用它
但我不确定我的代码是否正确,因为我的测试文件由于某种原因无法识别我的 exec。我在 learn.js 上的代码:
function qAsync(){
const doAsync = new doAsync(11500);
this.desc= "in order to wait 11.5 sec,call qAsync which calls asyncFun"
let exec= doAsync.exec(("hello after 11.5 sec"));
return (exec,doAsync);
}
let doAsync = async function (ms) {
return await new Promise(resolve => setTimeout(resolve,ms));
}
在 test.js 上:
function test4(){
let test = qAsync();
alert("first let us decribe the function:\n" + test.desc);
alert("Now we will run exec.");
test.exec(); //doesn't work and calls on built in exec and not mine
}
我怎样才能让我的测试工作,你认为我应该改进我的 qAsync 吗?
解决方法
感谢评论回答: 学习.js:
function qAsync(){
this.doAsync = function (ms) {
return new Promise(resolve => setTimeout(resolve,ms));
}
this.desc = "in order to wait 11.5 sec,call exec which calls doAsync,and see the print in the console"
this.exec = async function () {
await this.doAsync(11500);
console.log("did you see this after 11.5 sec?");
}
}
test.js:
async function test4(){
let test = new qAsync();
alert("first let us describe the function:\n"+test.desc);
alert("now we will run exec.");
await test.exec();
}