whitebird1016 / Web-Skills-6

Learning

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Web-Skills(6)

Shikamaru

Function Skills

1: Function self-execution

const Func = function() {}(); // Commonly used
(function() {})(); // Commonly used
(function() {}()); // Commonly used
[function() {}()];
+ function() {}();
- function() {}();
~ function() {}();
! function() {}();
new function() {};
new function() {}();
void function() {}();
typeof function() {}();
delete function() {}();
1, function() {}();
1 ^ function() {}();
1 > function() {}();

2: One-time function

function Func() {
    console.log("x");
    Func = function() {
        console.log("y");
    }
}

3: Lazy loading functions

function Func() {
    if (a === b) {
        console.log("x");
    } else {
        console.log("y");
    }
}
// replace with
function Func() {
    if (a === b) {
        Func = function() {
            console.log("x");
        }
    } else {
        Func = function() {
            console.log("y");
        }
    }
    return Func();
}

4: Detect non-null parameters

function IsRequired() {
    throw new Error("param is required");
}
function Func(name = IsRequired()) {
    console.log("I Love " + name);
}
Func(); // "param is required"
Func("You"); // "I Love You"

5: String creation function

const Func = new Function("name", "console.log(\"I Love \" + name)");

6: Handle error messages gracefully

try {
    Func();
} catch (e) {
    location.href = "https://stackoverflow.com/search?q=[js]+" + e.message;
}

7: Handle Async/Await parameters gracefully

function AsyncTo(promise) {
    return promise.then(data => [null, data]).catch(err => [err]);
}
const [err, res] = await AsyncTo(Func());

8: Handle multiple function return values gracefully

function Func() {
    return Promise.all([
        fetch("/user"),
        fetch("/comment")
    ]);
}
const [user, comment] = await Func();