如何在超时时拒绝解决承诺?

时间:2017-05-18 10:47:27

标签: node.js typescript es6-promise

我有一个承诺需要被拒绝,因为决心花了太长时间。在我的代码中,我试图使用超时来拒绝承诺。我遵循了Promise timeout tutorial的例子,但在超时后无法拒绝承诺。

/* I added setTimeout 10 seconds to the package to give it a delay */
const package = require('package');

const promiseTimeout = function(ms, promise){
  // Create a promise that rejects in <ms> milliseconds
  let timeout = new Promise((resolve, reject) => {
    let id = setTimeout(() => {
    clearTimeout(id);
    console.log("timeout finished at " + ms + "ms but promise won't reject");
    reject('Timed out in '+ ms + 'ms. - Reject Message')
    }, ms)
  })

  // Returns a race between our timeout and the passed in promise
  return Promise.race([
    promise,
    timeout
  ])
}

const prolongedPromise = function(){
    return new Promise((resolve, reject) => {
        package.asyncFunction(function(data) {
          resolve(data) /* Takes 10 seconds to resolve */
        })
    })
};

/* Attempting to race promises to get reject to execute on timeout */
let promiseRace = promiseTimeout(2000, prolongedPromise());
promiseRace.then(response => {
    resolve(response); /* Always resolves even after timeout is executed */
}, error => {
    reject(error);
}).catch(error => {
    reject(error);
})

我不确定但是承诺可能已经解决(10秒超时),这将不允许拒绝执行。

很难展示完整的环境,因为我必须按照软件包的API来获取数据。我有一个tester environment in github已准备好10秒等待asyc功能我试图解决,如果有人好奇完全看到问题。

我如何能够在超时时拒绝承诺?

0 个答案:

没有答案