Promise.timeout()

本文深入解析了WinJS.Promise.timeout方法的两种形式及其用法,包括如何创建超时承诺和自动取消超时承诺。
Promise.timeout method

This method has two forms: WinJS.Promise.timeout(timeout) and WinJS.Promise.timeout(timeout, promise)WinJS.Promise.timeout(timeout) creates a promise that is completed asynchronously after the specified timeout, essentially wrapping a call to setTimeout within a promise. WinJS.Promise.timeout(timeout, promise) sets a timeout period for completion of the specified promise, automatically canceling the promise if it is not completed within the timeout period.

Syntax


   
  1. promise.timeout(timeout, promise).done( /* Your success and error handlers */ );

Parameters

timeout

Type: Number

The timeout period in milliseconds. If this value is zero or not specified, msSetImmediate is called, otherwise setTimeout is called.

promise

Type: Promise

Optional. A promise that will be canceled if it doesn't complete within the timeout period.

Return value

Type:  Promise

If the promise parameter is omitted, returns a promise that will be fulfilled after the timeout period. If the promise paramater is provided, the same promise is returned.



### 关于 `this` 和 `setTimeout` 的使用 当在对象方法内部使用 `setTimeout` 函数时,可能会遇到上下文丢失的问题。这是因为 `setTimeout` 创建的新函数会在全局作用域中执行,这会导致 `this` 不再指向预期的对象。 为了保持正确的上下文,可以采用几种不同的解决方案: #### 方法一:绑定 `this` 通过 `.bind(this)` 显式地将当前的 `this` 绑定到回调函数上[^1]。 ```javascript function MyObject() { this.value = 42; this.method = function() { console.log('Value:', this.value); setTimeout(function() { console.log('Timeout value:', this.value); // Without bind, 'this' would refer to global object. }.bind(this), 1000); }; } const obj = new MyObject(); obj.method(); // After one second prints "Timeout value: 42" ``` #### 方法二:箭头函数 利用 ES6 引入的箭头函数特性来自动捕获外部的作用域中的 `this` 值。 ```javascript function MyObject() { this.value = 42; this.method = () => { console.log('Value:', this.value); setTimeout(() => { console.log('Arrow timeout value:', this.value); // Arrow functions inherit 'this' }, 1000); }; } ``` #### 方法三:保存 `this` 到变量 创建局部变量存储原始的 `this` 上下文,在回调内引用该变量而不是直接访问 `this`。 ```javascript function MyObject() { var self = this; // Store reference before entering nested scope this.value = 42; this.method = function() { console.log('Value:', this.value); setTimeout(function() { console.log('Local variable stored context:', self.value); }, 1000); }; } ``` 这些技术可以帮助开发者避免因错误理解 JavaScript 中 `this` 行为而导致的各种问题。值得注意的是,过度嵌套回调可能导致难以维护的代码结构——即所谓的“回调地狱”。因此建议合理规划异步逻辑流并考虑使用 Promise 或 async/await 来简化复杂的异步操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值