添加对象然后push

    技术2022-07-11  119

    添加对象然后push

    Promises were a revelation in JavaScript development, allowing us to enjoy async processing and avoid callback hell. Many new APIs like Battery API, Cache API, and others use the promise API. One fact you may not know is that you can add a then method to any object to make it Promise-like!

    承诺是JavaScript开发的启示,它使我们可以享受异步处理并避免回调地狱。 许多新的API(例如Battery API , Cache API和其他API)都使用promise API。 您可能不知道的一个事实是,您可以向任何对象添加then方法,使其类似于Promise!

    Let's create a generic object with a then method that accepts a resolve function as its argument:

    让我们用then方法创建一个通用对象,该方法接受一个resolve函数作为其参数:

    j = { then: resolve => fetch("/").then(resolve) }

    With an object featuring a then method, you can call the then method or use await syntax:

    对于具有then方法的对象,可以调用then方法或使用await语法:

    j.then(res => console.log(res)); // Response {type: "basic", url: "https://davidwalsh.name/", redirected: false, status: 200, ok: true, …} // ... or an await... const response = await j; // Response {type: "basic", url: "https://davidwalsh.name/", redirected: false, status: 200, ok: true, …}

    This technique is interesting and, under the right circumstances, can be employed to represent a logical usage.

    该技术很有趣,并且在适当的情况下可以用来表示逻辑用法。

    Hack or useful? How would you use this perk of then?

    哈克还是有用? 您将如何使用then特权?

    翻译自: https://davidwalsh.name/then-on-objects

    添加对象然后push

    相关资源:jdk-8u281-windows-x64.exe
    Processed: 0.014, SQL: 9