Javascript ES7异步/等待提取超时

Javascript ES7异步/等待提取超时,javascript,timeout,async-await,fetch-api,ecmascript-next,Javascript,Timeout,Async Await,Fetch Api,Ecmascript Next,我想在fetch方法中设置timeout 根据答案,我们可以自定义超时方法,如下所示 // Rough implementation. Untested. function timeout(ms, promise) { return new Promise(function(resolve, reject) { setTimeout(function() { reject(new Error("timeout")) }, ms) pro

我想在
fetch
方法中设置timeout

根据答案,我们可以自定义超时方法,如下所示

// Rough implementation. Untested.
function timeout(ms, promise) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      reject(new Error("timeout"))
    }, ms)
    promise.then(resolve, reject)
  })
}

timeout(1000, fetch('/hello')).then(function(response) {
  // process response
}).catch(function(error) {
  // might be a timeout error
})
并通过

但我想用ES7异步/等待语法调用该方法,我尝试了下面的方法,但失败了

async request() {
  try { 
    let res = await timeout(1000, fetch('/hello'));
  } catch(error) {
    // might be a timeout error
  }
}
我如何在ES7异步/等待语法中使用它

谢谢你抽出时间


更新 感谢您的回复,我将在http请求步骤中显示我的代码

ES7获取
您的
请求
功能似乎正在运行。怎么了?为什么你认为你失败了?我测试ES6获取并设置超时10毫秒,它捕捉到了我的错误。我在ES7 async/await fetch中尝试了我的上述语法,相同的10ms timeout参数,但是我在react本机控制台中得到了
可能未处理的承诺拒绝
错误。拒绝的原因是什么?我不太理解输出,当我在ES6 fetch中尝试超时时,我的捕获将在控制台中没有任何警告。但是现在输出有警告>>>
2016-06-08 22:07:11.606[warn][tid:com.facebook.React.JavaScript]可能未处理的承诺拒绝(id:0):assign的一个源在原型链上有一个可枚举键。这是一个我们不支持的边缘案例。此错误是一个性能优化错误,不符合规范。
请向我们展示整个代码。显然,您正在某处使用
Object.assign
,这会引发一个异常,由于某种原因,该异常不是在承诺链处理程序中捕获的,而是在异步函数的
catch
语句中捕获的。
超时
功能在这里不是罪魁祸首。
async request() {
  try { 
    let res = await timeout(1000, fetch('/hello'));
  } catch(error) {
    // might be a timeout error
  }
}
'use strict';

import { configApi, } from 'tyrantdb-config';
import { timeoutPromise, } from 'xd-utils-kit';

const keyResponse = configApi.keyResponse;
const KEY_DATA = keyResponse.data;


module.exports = {
  async fetchLogin(url, params, dataRely) {
    let {
      self, processor, route,
      storage, isLocalStoraged,
      email, password, _warning, } = dataRely;

    self.setState({ isWait: true, });

    try {
      let res = await timeoutPromise(10, fetch(url, params));
      if (res.status >= 200 && res.status < 300) {

        let resJson = await res.json();
        let resData = resJson[KEY_DATA];

        let cache = {
          ...resData,
          password,
        };
        if (isLocalStoraged !== true) {
          processor(cache, storage);
        }
        global.g_user = cache;
        self.setState({ isWait: false, });

        // clean user info which already bind to self[this]
        self.email = self.password = null;
        self.isLocalStoraged = false;
        route();

      } else {
        console.log(`[login] response code: ${res.status}`);
        self.setState({ isWait: false, });
        _warning();
      }
    } catch(error) {
      console.error(error);
    }
  },

  saveLoginState: (cache, storage) => {
    storage.save({
      key: 'loginState',
      rawData: cache,
    });
  },

  openURL: (url, Linking) => {
    Linking.canOpenURL(url).then(supported => {
      if (!supported) {
        console.log(`can\'t handle url: ${url}`);
      } else {
        return Linking.openURL(url);
      }
    }).catch((err) => {
      console.log(`error occurred: ${err}`);
    })
  },
};
'use strict';

import { configApi, } from 'tyrantdb-config';
import { timeoutPromise, } from 'xd-utils-kit';

const keyResponse = configApi.keyResponse;
const KEY_DATA = keyResponse.data;


module.exports = {
  fetchLogin(url, params, dataRely) {
    let {
      self, processor, route,
      storage, isLocalStoraged,
      email, password, _warning, } = dataRely;

    self.setState({ isWait: true, });

    timeoutPromise(1000, fetch(url, params))
      .then((res) => {
        if (res.status >= 200 && res.status < 300) {
          return res.json();
        } else {
          console.log(`[login] response code: ${res.status}`);
          self.setState({ isWait: false, });
          _warning();
        }
      })
      .then((resJson) => {
        let resData = resJson[KEY_DATA];

        let cache = {
          ...resData,
          password,
        };
        if (isLocalStoraged !== true) {
          processor(cache, storage);
        }
        global.g_user = cache;
        self.setState({ isWait: false, });

        // clean user info which already bind to self[this]
        self.email = self.password = null;
        self.isLocalStoraged = false;
        route();
      })
      .catch(error => console.error(error))
      .done();
  },

  saveLoginState: (cache, storage) => {
    storage.save({
      key: 'loginState',
      rawData: cache,
    });
  },

  openURL: (url, Linking) => {
    Linking.canOpenURL(url).then(supported => {
      if (!supported) {
        console.log(`can\'t handle url: ${url}`);
      } else {
        return Linking.openURL(url);
      }
    }).catch((err) => {
      console.log(`error occurred: ${err}`);
    })
  },
};
2016-06-08 22:50:59.789 [info][tid:com.facebook.React.JavaScript] [login] response code: 400
2016-06-08 22:50:59.808 [error][tid:com.facebook.React.JavaScript] { [TypeError: undefined is not an object (evaluating 'KEY_DATA')]
  line: 103795,
  column: 29,
  sourceURL: 'http://172.26.129.189:8081/index.ios.bundle?platform=ios&dev=true' }
2016-06-08 22:50:59.810 [error][tid:com.facebook.React.JavaScript] One of the sources for assign has an enumerable key on the prototype chain. This is an edge case that we do not support. This error is a performance optimization and not spec compliant.
2016-06-08 22:50:59.810 [info][tid:com.facebook.React.JavaScript] 'Failed to print error: ', 'One of the sources for assign has an enumerable key on the prototype chain. This is an edge case that we do not support. This error is a performance optimization and not spec compliant.'