我正在尝试将此代码转换为没有"async - await"的版本。转换为使用(所有)承诺而不使用async和await的代码。但我的控制台打印时间未定义。有人能帮帮我吗?这是我大学的家庭作业。非常感谢
(async() => {
function exibirErro(err) {
console.log(err.message);
}
const f1 = async(tempo) => {
return new Promise((resolve, reject) => {
const f = () => reject(new Error('Rejeitado'));
console.log(`Aguardando ${tempo} segundos...`);
setTimeout(f, tempo);
});
};
const f2 = async(x) => {
if ((Math.random() * 10) % 2 == 0) {
throw new Error('Ops');
}
return Promise.resolve(1000 * x);
};
const f3 = async() => {
const r = await new Promise(resolve => resolve(2));
const t = await f2(r);
await f1(t);
};
try {
await f3();
} catch (err) {
exibirErro(err);
}
})();
我代码:
function exibirErro(err) {
console.log(err.message);
}
function f1(tempo) {
return new Promise((resolve, reject) => {
const f = () => reject(new Error('Reject'));
console.log(`wait ${tempo} seconds...`);
setTimeout(f, tempo);
})
.then((x) => {
if ((Math.random() * 10) % 2 == 0) {
throw new Error('Ops');
}
return Promise.resolve(1000 * x);
})
.then((t) => {
return Promisse.resolve(f1(t));
}).catch((e) => {
exibirErro(e);
})
}
f1();
从包装器函数开始-
(async() => {
首先我们有一个普通的同步函数,这里没有什么要改变的-
function exibirErro(err) {
console.log(err.message);
}
接下来我们有函数f1
,它使用async
关键字,但没有await
任何东西。您只需删除async
关键字-
const f1 = async(tempo) => {
return new Promise((resolve, reject) => {
const f = () => reject(new Error('Rejeitado'));
console.log(`Aguardando ${tempo} segundos...`);
setTimeout(f, tempo);
});
};
接下来我们有函数f2
,它再次使用async
,但没有await
任何东西。删除async
-
const f2 = async(x) => {
if ((Math.random() * 10) % 2 == 0) {
throw new Error('Ops');
}
return Promise.resolve(1000 * x);
};
然后我们有f3
函数await
有两个东西,r
和t
-
const f3 = async() => {
const r = await new Promise(resolve => resolve(2));
const t = await f2(r);
await f1(t); // missing return
};
我们可以用.then
-
f3
const f3 = () =>
new Promise(resolve => resolve(2)).then(r =>
f2(r).then(t =>
f1(t)
)
)
最后是try
/catch
-
try {
await f3();
} catch (err) {
exibirErro(err);
}
用.catch
代替-
f3().catch(exibirErro)
和async
包装器函数的关闭语法。最终版本将不需要包装器。
})();
现在都在这里了-
function exibirErro(err) {
console.log(err.message);
}
const f1 = tempo => {
return new Promise((resolve, reject) => {
const f = () => reject(new Error('Rejeitado'));
console.log(`Aguardando ${tempo} segundos...`);
setTimeout(f, tempo);
});
};
const f2 = x => {
if ((Math.random() * 10) % 2 == 0) {
throw new Error('Ops');
}
return Promise.resolve(1000 * x);
};
const f3 = () => {
return new Promise(resolve => resolve(2)).then(r =>
f2(r).then(t =>
f1(t)
)
)
}
f3().catch(exibirErro)