基本上,我想尝试了解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!!') })
更多推荐
那么如何使异步呢?
发布评论