如何解决延后承诺
我有这个问题,我似乎不知道该如何解决?编写一个承诺的函数,它接受一个值。此函数将返回一个承诺,该承诺将在2秒后解决。以下代码不应编辑,而应使用promise对象。
function promised (val) {
}
// UNCOMMENT THESE TO TEST YOUR WORK!
const createPromise = promised('wait for it...');
createPromise.then((val) => console.log(val));
// will log "wait for it..." to the console after 2 seconds
解决方法
const sleep = async (time) => {
return new Promise(resolve => setTimeout(resolve,time * 1000))
}
const sayHello = async () => {
await sleep(2)
console.log('Hello there')
}
sayHello()
以下是说明:
使用setTimeout()
是一种内置方法,它在指定的毫秒数后调用函数或对表达式求值。
setTimeout()
接受2个参数,第一个是回调函数,第二个是毫秒数。
1秒= 1000ms,所以2秒= 2000ms,依此类推
function promised (val) {
// Create a new promise and resolve val after 2 seconds
return new Promise(resolve => setTimeout(() => resolve(val),2000)) //2000ms => 2 seconds
}
const createPromise = promised('wait for it...') // Pass in your message to promised function
createPromise
.then(val => console.log(val))
// Catch errors if any you don't need it here since we are always resolving the promise i just included it here so you know it's exist
.catch(err => console.log(err))
除非您100%确信诺言将始终得以解决,否则应始终使用.catch
示例:
function greeting(name) {
return new Promise((resolve,reject) => setTimeout(() => {
try {
if (name.length <= 2) {
throw new Error('Name must be more than two characters')
}
} catch (msg) {
reject(msg)
}
resolve(`Hello ${name}`)
},2000))
}
greeting('ab')
.then(res => console.log(res))
.catch(err => console.log(err)) // Error: Name must be more than two characters
greeting('John')
.then(res => console.log(res)) // Hello John
.catch(err => console.log(err))
使用异步,等待:
const greetSomeone = async (name) => {
try {
// Note that you can't use await outside an async function
const msg = await greeting(name)
console.log(msg)
} catch (err) {
console.log(err)
}
}
greetSomeone('ac') // Error: Name must be more than two characters
greetSomeone('Michael') // Hello Michael
了解有关承诺https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
的更多信息版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。