JavaScript专项算法题(6)(Promises)

@冒泡的马树
题库原地址:http://csbin.io/promises
Promises期约 挑战1 问题:
【JavaScript专项算法题(6)(Promises)】让我们从复习异步函数开始吧!使用setTimeout,在1000ms后打印字符串“Hello!”。
题解:

// Challenge 1function sayHello() { // ADD CODE HERE setTimeout(() => console.log('Hello!'), 1000) }// Uncomment the line below when ready sayHello(); // should log "Hello" after 1000ms

挑战2 问题:
创建一个promise。延迟1000ms后在resolve里面传入值“Resolved!”,使用setTimeout。在promise被调用resolve后,打印它的内容,借助传入console.log到.then中来实现。
题解:
// Challenge 2 var promise = new Promise(function (resolve, reject) { // ADD CODE HERE setTimeout(() => resolve('Resolved'), 1000) }); // Should print out "Resolved!" // ADD CODE HERE promise.then(res => console.log(res))

挑战3 问题:
创建另外一个promise。这次不使用setTimeout,在reject里面传入值“Rejected!”。在promise被调用reject之后,打印它的内容,借助传入console.log到.catch来实现。
题解:
// Challenge 3promise = new Promise(function(resolve, reject) { // ADD CODE HERE reject('Rejected') })// Should print out "Reject!" // ADD CODE HERE promise.catch(res => console.log(res))

挑战4 问题:
Promises期约是异步的。现在让我们来证明它们确实如此!创建一个promise,在resolve里面传入值“Promise has been resolved!”,然后去掉挑战4底部的注释。运行后我们看到的打印顺序是怎样的?“Promise has been resolved!”先还是"I'm not the promise!"先?为什么?
题解:
// Challenge 4promise = new Promise(function (resolve, reject) { // ADD CODE HERE resolve() }); // Uncomment the lines below when ready promise.then(() => console.log('Promise has been resolved!')); console.log("I'm not the promise!");

挑战5 问题:
编写delay函数,用于返回一个promise。此返回promise应该返回一个在1000ms后调用resolve的setTimeout。
题解:
// Challenge 5 function delay(){ return new Promise(function (resolve, reject) { return setTimeout(resolve, 1000) }) }// Uncomment the code below to test // This code should log "Hello" after 1000ms delay().then(sayHello);

挑战6 问题:
在这个挑战中我们会使用.then链式调用promises期约。创建两个变量:firstPromise和secondPromise,让secondPromise成为一个在resolve中传值“Second!”的promise,firstPromise则在resolve中传入secondPromise。用.then的方式调用firstPromise,这会返回secondPromise,然后在它的resolve执行之后,打印对应promise的内容,借助传入console.log到.then来实现。
题解:
// Challenge 6 // // ADD CODE BELOW var secondPromise = Promise.resolve('Second!') var firstPromise = new Promise(function (resolve, reject) { resolve(secondPromise) }) firstPromise.then().then(res => console.log(res))

挑战7 问题:
我们有一个会从数据库拉取数据的API,它接收一个下标参数然后返回一个promise。你的挑战是使用promise.all发起3次API调用,然后在调用都结束后返回对应的数据。
题解:
// Challenge 7 const fakePeople = [ { name: 'Rudolph', hasPets: false, currentTemp: 98.6 }, { name: 'Zebulon', hasPets: true, currentTemp: 22.6 }, { name: 'Harold', hasPets: true, currentTemp: 98.3 }, ]const fakeAPICall = (i) => { const returnTime = Math.floor(Math.random() * 1000); return new Promise((resolve, reject) => { if (i >= 0 && i < fakePeople.length) { setTimeout(() => resolve(fakePeople[i]), returnTime); } else { reject({ message: "index out of range" }); } }); }; function getAllData() { // CODE GOES HERE return Promise.all([fakeAPICall(0), fakeAPICall(1), fakeAPICall(2)]) }getAllData().then(res => console.log(res))


    推荐阅读