如何在一定时间后超时承诺?我知道Q有一个承诺超时,但我使用的是本机NodeJS承诺而且它们没有.timeout函数.
我错过了一个或其包装不同吗?
或者,下面的实现是否有利于不吸收内存,实际上按预期工作?
我也可以以某种方式将其全局包装,以便我可以将它用于我创建的每个承诺,而不必重复setTimeout和clearTimeout代码?
function run() {
logger.info('DoNothingController working on process id {0}...'.format(process.pid));
myPromise(4000)
.then(function() {
logger.info('Successful!');
})
.catch(function(error) {
logger.error('Failed! ' + error);
});
}
function myPromise(ms) {
return new Promise(function(resolve, reject) {
var hasValueReturned;
var promiseTimeout = setTimeout(function() {
if (!hasValueReturned) {
reject('Promise timed out after ' + ms + ' ms');
}
}, ms);
// Do something, for example for testing purposes
setTimeout(function() {
resolve();
clearTimeout(promiseTimeout);
}, ms - 2000);
});
}
Run Code Online (Sandbox Code Playgroud)
谢谢!
我使用的是Node.js和TypeScript,我正在使用它async/await.这是我的测试用例:
async function doSomethingInSeries() {
const res1 = await callApi();
const res2 = await persistInDB(res1);
const res3 = await doHeavyComputation(res1);
return 'simle';
}
Run Code Online (Sandbox Code Playgroud)
我想为整个功能设置超时.即如果res1需要2秒,res2需要0.5秒,res3需要5秒我想要超时,3秒后让我抛出错误.
正常setTimeout调用是一个问题,因为范围丢失:
async function doSomethingInSeries() {
const timerId = setTimeout(function() {
throw new Error('timeout');
});
const res1 = await callApi();
const res2 = await persistInDB(res1);
const res3 = await doHeavyComputation(res1);
clearTimeout(timerId);
return 'simle';
}
Run Code Online (Sandbox Code Playgroud)
我无法正常地抓住它Promise.catch:
doSomethingInSeries().catch(function(err) {
// errors in res1, res2, res3 will be …Run Code Online (Sandbox Code Playgroud) 使用超时实现函数调用
我已经看到许多资源提供Promise.race了在给定时间段内使用超时函数调用的类似示例.这是如何Promise.race在实践中使用的一个很好的例子.这是一些示例代码:
function doWithinInterval(func, timeout) {
var promiseTimeout = new Promise(function (fulfill, reject) {
// Rejects as soon as the timeout kicks in
setTimeout(reject, timeout);
});
var promiseFunc = new Promise(function (fulfill, reject) {
var result = func(); // Function that may take long to finish
// Fulfills when the given function finishes
fulfill(result);
});
return Promise.race([promiseTimeout, promiseFunc]);
}
Run Code Online (Sandbox Code Playgroud)
上面使用的简单方法Promise.race一旦超时func完成就会拒绝承诺.否则,一旦func函数在超时间隔之前完成,项目就会完成.
这听起来不错,易于使用.
但是,这是在Promise中使用超时的最佳做法吗?
当然,如果我们想使用Promises为函数调用设置超时,可以使用上面的方法.这些行动似乎仍然是一个很好的承诺.但是,这被认为是在Promise中使用超时的好方法吗?如果没有,使用它的缺点是什么?
我正在寻找替代方法,但找不到本机的Promise方法来做到这一点.
相反,一些外部Promise库提供timeout如下功能:
蓝鸟供应.timeout() …
promise ×3
javascript ×2
node.js ×2
async-await ×1
ecmascript-6 ×1
es6-promise ×1
settimeout ×1
timeout ×1
typescript ×1