那么如何使异步呢? [英] How to make an async then?
问题描述
基本上,我想尝试了解JS
中的async/await
和promise
的更多信息.我正在尝试使你好介于完成!和第三名之间!.因此,最好的猜测是,使第二个then
为asnyc并等待console.log('Hello')
.我在下面尝试了两种方法,但是两种方法都无法正常工作.
Basically I am trying to play around to understand more of async/await
and promise
in JS
. I'm trying to make Hello comes in between finished! and third finish!!. So the best guess is, making second then
asnyc and await for console.log('Hello')
. I've tried both ways below but both are not working as expected.
方法A
let promise = new Promise((res,rej)=>{
res();
});
promise.then(() => {
console.log('finished!')
}).then(() => {
setTimeout(async function(){
await console.log("Hello"); }, 3000); //async/await at setTimeout level
}).then(() => {
console.log('third finish!!')
})
方法B:
let promise = new Promise((res,rej)=>{
res();
});
promise.then(() => {
console.log('finished!')
}).then(async () => { //async/await at thenlevel
await setTimeout(function(){
console.log("Hello"); }, 3000);
}).then(() => {
console.log('third finish!!')
})
推荐答案
您需要第二部分是Promise
,并从.then
返回它,以便在第一部分和第三部分之间正确链接. setTimeout
不返回Promise
,您必须显式构造一个Promise
:
You need the second section to be a Promise
, and return it from the .then
so that it's properly chained between the first and the third. setTimeout
doesn't return a Promise
, you have to explicitly construct a Promise
instead:
let promise = new Promise((res,rej)=>{
res();
});
promise.then(() => {
console.log('finished!')
}).then(() => {
return new Promise(resolve => {
setTimeout(function(){
console.log("Hello");
resolve();
}, 1000);
});
}).then(() => {
console.log('third finish!!')
})
或者,使用await
,使用await new Promise
,然后使用相同的Promise构造和setTimeout
:
Or, using await
, use await new Promise
followed by the same Promise construction and the setTimeout
:
let promise = new Promise((res, rej) => {
res();
});
promise.then(() => {
console.log('finished!')
}).then(async() => {
await new Promise(resolve => {
setTimeout(function() {
console.log("Hello");
resolve();
}, 1000);
});
}).then(() => {
console.log('third finish!!')
})
这篇关于那么如何使异步呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!