【发布时间】:2018-03-27 07:28:15
【问题描述】:
JavaScript 异步函数返回 Promise,但也执行该函数。这有点违背了目的。请解释。还有一种方法可以通过仅使用 async/await(不是 Promise)来返回 Promise 而不是执行。
https://jsfiddle.net/ravilution/woxkossp/
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
const fn = async (value) => {
console.log("start fn ", value)
wait(2000);
console.log("end fn ", value)
return value;
}
const main = async () => {
var promiseForFn = fn(3);
console.log("promiseForFn ", promiseForFn);
var value = await promiseForFn;
console.log("value ", value);
}
main()
或
https://jsfiddle.net/ravilution/o44kbj9p/
const wait = async(ms) => {
var start = new Date().getTime();
var end = start;
while (end < start + ms) {
end = new Date().getTime();
}
}
const fn = async(value) => {
console.log("start fn ", value)
await wait(2000);
console.log("end fn ", value)
return value;
}
const main = async() => {
var promiseForFn = fn(3);
console.log("promiseForFn ", promiseForFn);
var value = await promiseForFn;
console.log("value ", value);
}
main()
将函数标记为
async并不是让它真正异步的原因是答案。感谢@another-guy
【问题讨论】:
-
您的
wait函数是同步的。当您从fn使用它时,您期望会发生什么? -
@another-guy 请帮助我理解。我将等待转换为异步。似乎仍然没有按预期工作。 jsfiddle.net/ravilution/o44kbj9p
标签: javascript node.js async-await