在学习 promise 之前我们先要理解什么是回调地狱。因为正是为了解决回调地狱这一问题,promise 才出现了
阅读下面的文章,回顾什么是回调,以及回调地狱是什么
实现延时
/** * @param {number} milliseconds */ const sleep = (milliseconds) => { // your code here }; //测试用例 sleep(2000).then(() => { //下面这句话会在执行了2s延时之后打印出来 console.log("我延时了2s"); });
const randomSleep = () => { // your code here }; //测试用例 console.log("STEP 1"); randomSleep().then(() => { // randomSleep()函数执行完毕才打印 B console.log("STEP 2"); }); console.log("STEP 3");
打印结果如下:
STEP 1 STEP 3 STEP 2
使用 Promise 模拟数据获取.假设您需要获取北京的天气信息
{ city: "beijing", temperature: 2 }
const fakeFetchWeather = (endpoint) => { // TODO: 实现模拟获取天气信息 }; // 测试用例 fakeFetchWeather("beijing") .then((data) => { console.log(data); }) .catch((error) => { console.error(error); }); //{ city:"beijing", temperature: 2} fakeFetch("Paris") .then((data) => { console.log(data); }) .catch((error) => { console.error(error); }); //接口信息错误
按照要求实现 mergePromise 函数,把传进去的函数数组按顺序先后执行,并且把返回的数据先后放到数组 data 中。 编写 JavaScript 代码,跑通如下测试用例
const timeout = (ms) => new Promise((resolve, reject) => { setTimeout(() => { resolve(); }, ms); }); const ajaxA = () => timeout(2000).then(() => { console.log("A"); return A; }); const ajaxB = () => timeout(1000).then(() => { console.log("B"); return B; }); const ajaxC = () => timeout(2000).then(() => { console.log("C"); return C; }); const mergePromise = (fetchArray) => { // 在这里实现你的代码 }; //测试用例 mergePromise([fakeFetchWeather(), fakeFetchWeather(), fakeFetchWeather()]).then( (data) => { console.log("done"); console.log(data); // data 为 [A, B, C] } ); // 要求分别输出 // A // B // C // done // [A, B, C]
把你觉得此次学习中做得最好的代码放在 Github 后进行提交。
依然把今天的学习用时,收获,问题进行记录。
更多相关技术内容咨询欢迎前往并持续关注六星社区了解详情。
长按或扫描下方二维码,免费获取 Python公开课和大佬打包整理的几百G的学习资料,内容包含但不限于Python电子书、教程、项目接单、源码等等
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!