添加对象然后push_然后在对象上

添加对象然后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 APICache 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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值