那么如何使异步呢?

编程入门 行业动态 更新时间:2024-10-18 12:23:44
本文介绍了那么如何使异步呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

基本上,我想尝试了解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!!') })

更多推荐

那么如何使异步呢?

本文发布于:2023-11-13 00:33:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1582916.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!