[英]Javascript Async/Await program order
const function1 = () => new Promise(function(resolve,reject) { setTimeout(() => { resolve(10) },6000) }); const function2 = async () => { console.log("first"); const val = await function1() console.log("second"); return val } console.log("third -- " ,function2())
我正在考虑以下消息的顺序:
first
second
third -- Promise { <pending> }>
但是事实证明是这样的:
first
third -- Promise { <pending> }
second
谁能帮我理解这一点?
而不是调用function2()
您需要await
它
await function2(); // logs first (6 seconds expire) second, 10
这是因为您需要先等待功能2解决Promise,然后才能继续
您可以执行以下操作以获得所需的结果
const function3 = async () => {
const third = await function2();
console.log( "third --", third )
}
function3();
尝试下一个代码
const function1 = () =>
new Promise(function (resolve, reject) {
setTimeout(() => {
resolve(10)
}, 6000)
});
const function2 = async () => {
console.log("first");
const val = await function1()
console.log("second");
return val;
}
const start = async () => {
console.log("third -- ", await function2());
};
start();
在日志好友中:)!
第三个单词的日志记录为第二个。 因为带有单词“ second ”的日志在function2内部被解析,这被称为常规函数 。 这段代码基本上假设您对函数2的(异步)结果不感兴趣,因此它只是重新调整了未完成的Promise。
每当您需要异步函数的结果(而不是挂起的promise)时,都应始终await
其链then()
中await
它,您可以在其中记录最终结果,在这种情况下为10。
您的代码说明
的console.log( “第一”); -首先,我希望没有问题
当解释器看到此行时const val = await function1()
-它在这里等待并继续使用console.log("third -- " ,function2())
执行同步代码,您可以看到third -- Promise { <pending> }
比诺言正在解决,异步部分的执行仍在继续,您最终可以看到console.log("second");
要达到预期的行为,请尝试以下操作:
const function1 = () => new Promise(function(resolve,reject) { setTimeout(() => { resolve(10) },6000) }); const function2 = async () => { console.log("first"); const val = function1() console.log("second"); return val } console.log("third -- " , function2())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.