我有两个正在写JS的文件:学习和测试。学习后,我尝试创建一个asyc函数,该函数将执行以下操作:
开发一个名为"qAsync
"的"函数声明">
返回一个由两个键组成的对象(通过构造函数构建(:
- "
doAsync
":函数:返回可以使用async/await语法使用的setTimeout
函数 - "
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));
}
测试.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吗?
感谢评论回答:learn.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();
}