Promise
function sleep(t){
return new Promise((resolve)=>setTimeout(resolve,t))
}
console.time("休眠1秒");
sleep(1000).then(()=>console.timeLog("休眠1秒"))
Promise.resolve
Promise.resolve(1).then(console.log); // 輸出1
new Promise((resolve,reject)=>resolve(1)).then(console.log); // 輸出1
Promise.reject
Promise.reject(1).catch(console.error); // 輸出錯誤1
new Promise((resolve,reject)=>reject(1)).catch(console.error); // 輸出錯誤1
Promise.all
function sleep(t){
return new Promise((resolve)=>setTimeout(resolve,t))
}
Promise.all([
sleep(2000).then(()=>{
console.log(1);
return 2;
}),
sleep(3000).then(()=>{
console.log(3);
return 4;
}),
]).then((v)=>console.log(v))
// 1 2 [3,4]
Promise.race
function sleep(t){
return new Promise((resolve)=>setTimeout(resolve,t))
}
Promise.race([
sleep(2000).then(()=>{
console.log(1);
return 2;
}),
sleep(3000).then(()=>{
console.log(3);
return 4;
}),
]).then((v)=>console.log(v))
// 1 2 3
配合 async/await
// 休眠
function sleep(t){
return new Promise((resolve)=>setTimeout(resolve,t))
}
// 獲取包數(shù)據(jù)
async function queryData(name){
let result = await fetch(`https://unpkg.com/${name}/package.json`)
return await result.json()
}
async function print(obj,key){
console.log(key,obj);
}
// 展示一個對象
async function printAll(obj,key=''){
if(obj?.constructor===Array || typeof obj === "object"){
key&&console.group(key)
for(let skey in obj){
await printAll(obj[skey],obj?.constructor===Array?'':translate(skey))
}
key&&console.groupEnd(key)
}else{
print(obj,translate(key));
}
}
function translate(str){
return {
name:'名稱',
version:'版本',
main:'主文件',
unpkg:'cdn unpkg 默認(rèn)文件',
jsdelivr:'cdn jsdelivr 默認(rèn)文件',
typings:'ts 類型',
files:'npm 包文件列表',
dependencies:'依賴',
description:'描述',
devDependencies:'開發(fā)依賴',
scripts:'腳本' ,
module:'ES6 Module 主文件',
repository:'源碼地址',
license:'許可證',
engines:'編譯器',
author:'作者',
}[str]||str
}
async function show(name){
const package = await queryData(name);
await printAll(package,name);
}
(async function(list){
for(let i in list){
await show(list[i]);
}
})(["vue","react",'@qadd/css'])