亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

延遲后的承諾

延遲后的承諾

繁花如伊 2023-03-18 17:17:06
我有這個問題,我似乎不知道如何解決?寫一個函數,承諾,接受一個值。此函數將返回一個承諾,該承諾將在 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
查看完整描述

1 回答

?
天涯盡頭無女友

TA貢獻1831條經驗 獲得超9個贊

const sleep = async (time) => {

? ? return new Promise(resolve => setTimeout(resolve, time * 1000))

}




const sayHello = async () => {

? ? await sleep(2)

? ? console.log('Hello there')

}



sayHello()

這是解釋:


使用setTimeout()which 是一種內置方法,可在指定的毫秒數后調用函數或計算表達式。 setTimeout()有兩個參數,第一個是回調函數,第二個是毫秒數。1 秒 = 1000 毫秒所以 2 秒 = 2000 毫秒等等


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))?

你應該總是使用 .catch 除非你 100% 確定承諾總是會解決


例子:


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


查看完整回答
反對 回復 2023-03-18
  • 1 回答
  • 0 關注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號